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
1534D
1534
D
ru
D. Потерянное дерево
<div class="problem-statement"><div class="header"><div class="title">D. Потерянное дерево</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это интерактивная задача.</span></p><p>Маленький Дорми на фестивале столкнулся со странной головоломкой: ему нужно угадать ребра невзвешенного дерева из $$$n$$$ вершин! Вершины дерева пронумерованы от $$$1$$$ до $$$n$$$.</p><p>Ему разрешается задавать организатору вопросы одного вида:</p><ul><li> Маленький Дорми выбирает вершину $$$r$$$ ($$$1 \le r \le n$$$), а организатор в ответ предоставляет ему массив целых чисел $$$d_1, d_2, \ldots, d_n$$$, где $$$d_i$$$ — длина кратчайшего пути из $$$r$$$ в вершину $$$i$$$ для всех $$$1 \le i \le n$$$.</li></ul><p>Кроме того, чтобы <span class="tex-font-style-striked">сделать головоломку нечестной</span> дополнительно озадачить Дорми, организатор разрешает задать не более $$$\lceil\frac{n}{2}\rceil$$$ вопросов, где $$$\lceil x \rceil$$$ обозначает наименьшее целое число, большее либо равное $$$x$$$.</p><p>Маленький Дорми переживает, что может не угадать дерево, поэтому ему нужна ваша помощь!</p><p>Обратите внимание, что организатор создает дерево до начала взаимодействия, и не меняет его в процессе взаимодействия.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$2 \le n \le 2\,000$$$) — количество вершин в дереве.</p><p>После этого начинается взаимодействие.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Когда ваша программа нашла дерево, выведите одну строку, содержащую «<span class="tex-font-style-tt">!</span>», а затем $$$n-1$$$ строку, каждая из которых содержит два целых числа $$$a$$$ и $$$b$$$, означающие ребро, соединяющее вершины $$$a$$$ и $$$b$$$ ($$$1 \le a, b \le n$$$). После этого ваша программа должна сбросить буфер вывода и завершиться.</p><p>Вы можете выводить ребра дерева в любом порядке, ребро $$$(a,b)$$$ и ребро $$$(b,a)$$$ считаются одним и тем же ребром. Вывод ответа не считается как один из вопросов.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>После чтения количества вершин, вы можете задать не более $$$\lceil\frac{n}{2}\rceil$$$ вопросов. Каждый вопрос задается в формате «<span class="tex-font-style-tt">? r</span>», где целое число $$$r$$$ ($$$1 \le r \le n$$$) обозначает номер вершины, которую вы выбрали для этого вопроса.</p><p>После этого считайте $$$n$$$ целых чисел $$$d_1, d_2, \ldots, d_n$$$ в отдельной строке, где $$$d_i$$$ равно длине кратчайшего пути из вершины $$$r$$$ в вершину $$$i$$$.</p><p>После вывода запроса не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul> <li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++; </li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java; </li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal; </li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python; </li><li> смотрите документацию для других языков. </li></ul><p><span class="tex-font-style-bf">Если в какой-то момент вы задали больше, чем $$$\lceil \frac{n}{2} \rceil$$$ вопросов, взаимодействие прекратится, и вы получите вердикт «Неправильный ответ».</span></p><p><span class="tex-font-style-bf">Взломы</span></p><p>Чтобы взломать решение, используйте следующий формат теста.</p><p>Первая строка содержит целое число $$$n$$$ ($$$2 \le n \le 2\,000$$$).</p><p>Следующие $$$n−1$$$ строк содержат два целых числа $$$u$$$ и $$$v$$$ ($$$1 \le u,v \le n$$$), обозначающие ребро между вершинами $$$u$$$ и $$$v$$$ ($$$u \neq v$$$). Эти $$$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 0 1 2 2 1 0 1 1</pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 1 ? 2 ! 4 2 1 2 2 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 2 2 1 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 5 ! 4 5 3 5 2 4 1 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ниже показано дерево из первого примера.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8b00b9d47a8f65effb1b7cd0e2afa71157398819.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Обратите внимание, что ребра можно выводить в любом порядке.</p><p>Кроме того, ниже показаны ответы для всех возможных вопросов в примере $$$1$$$:</p><ul><li> $$$1$$$: $$$[0,1,2,2]$$$ </li><li> $$$2$$$: $$$[1,0,1,1]$$$ </li><li> $$$3$$$: $$$[2,1,0,2]$$$ </li><li> $$$4$$$: $$$[2,1,2,0]$$$</li></ul><p>Ниже показано дерево из второго примера.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/d6cca8f88d77aec46d7fda1dfd0498d1a7b8e07f.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Далее показаны ответы для всех возможных вопросов в примере $$$2$$$:</p><ul><li> $$$1$$$: $$$[0,4,1,3,2]$$$ </li><li> $$$2$$$: $$$[4,0,3,1,2]$$$ </li><li> $$$3$$$: $$$[1,3,0,2,1]$$$ </li><li> $$$4$$$: $$$[3,1,2,0,1]$$$ </li><li> $$$5$$$: $$$[2,2,1,1,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="13b1216341d310e99e242f6db4cf1c09"/> <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="b150642e1956e0532d7222198d59b78be2e7089e"/> <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='13b1216341d310e99e242f6db4cf1c09'>&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=""><a href="/latoken"><img style="height:60px !important;" src="https://latoken.com/_next/static/images/logo-full-dark-fe9406036648016c182d997e0a40986d.svg"/></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%2F1534%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='13b1216341d310e99e242f6db4cf1c09'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1534">Codeforces LATOKEN Round 1 (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='13b1216341d310e99e242f6db4cf1c09'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1534/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *1800 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='13b1216341d310e99e242f6db4cf1c09'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1015232"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='13b1216341d310e99e242f6db4cf1c09'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1015232"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91617" title="91617" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13946" resourceName="91617" resourceManual="true" src="//codeforces.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/91760" title="Codeforces LATOKEN Round 1 (Div. 1 + Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13884" resourceName="Codeforces LATOKEN Round 1 (Div. 1 + Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1534">Задачи</a></li> <li><a href="/contest/1534/submit">Отослать</a></li> <li><a href="/contest/1534/my">Мои посылки</a></li> <li><a href="/contest/1534/status">Статус</a></li> <li><a href="/contest/1534/hacks">Взломы</a></li> <li><a href="/contest/1534/room/1">Комната</a></li> <li><a href="/contest/1534/standings">Положение</a></li> <li><a href="/contest/1534/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_56cc65e8bc548312037510b1caf90523360153ae"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Потерянное дерево</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это интерактивная задача.</span></p><p>Маленький Дорми на фестивале столкнулся со странной головоломкой: ему нужно угадать ребра невзвешенного дерева из $$$n$$$ вершин! Вершины дерева пронумерованы от $$$1$$$ до $$$n$$$.</p><p>Ему разрешается задавать организатору вопросы одного вида:</p><ul><li> Маленький Дорми выбирает вершину $$$r$$$ ($$$1 \le r \le n$$$), а организатор в ответ предоставляет ему массив целых чисел $$$d_1, d_2, \ldots, d_n$$$, где $$$d_i$$$ — длина кратчайшего пути из $$$r$$$ в вершину $$$i$$$ для всех $$$1 \le i \le n$$$.</li></ul><p>Кроме того, чтобы <span class="tex-font-style-striked">сделать головоломку нечестной</span> дополнительно озадачить Дорми, организатор разрешает задать не более $$$\lceil\frac{n}{2}\rceil$$$ вопросов, где $$$\lceil x \rceil$$$ обозначает наименьшее целое число, большее либо равное $$$x$$$.</p><p>Маленький Дорми переживает, что может не угадать дерево, поэтому ему нужна ваша помощь!</p><p>Обратите внимание, что организатор создает дерево до начала взаимодействия, и не меняет его в процессе взаимодействия.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$2 \le n \le 2\,000$$$) — количество вершин в дереве.</p><p>После этого начинается взаимодействие.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Когда ваша программа нашла дерево, выведите одну строку, содержащую «<span class="tex-font-style-tt">!</span>», а затем $$$n-1$$$ строку, каждая из которых содержит два целых числа $$$a$$$ и $$$b$$$, означающие ребро, соединяющее вершины $$$a$$$ и $$$b$$$ ($$$1 \le a, b \le n$$$). После этого ваша программа должна сбросить буфер вывода и завершиться.</p><p>Вы можете выводить ребра дерева в любом порядке, ребро $$$(a,b)$$$ и ребро $$$(b,a)$$$ считаются одним и тем же ребром. Вывод ответа не считается как один из вопросов.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>После чтения количества вершин, вы можете задать не более $$$\lceil\frac{n}{2}\rceil$$$ вопросов. Каждый вопрос задается в формате «<span class="tex-font-style-tt">? r</span>», где целое число $$$r$$$ ($$$1 \le r \le n$$$) обозначает номер вершины, которую вы выбрали для этого вопроса.</p><p>После этого считайте $$$n$$$ целых чисел $$$d_1, d_2, \ldots, d_n$$$ в отдельной строке, где $$$d_i$$$ равно длине кратчайшего пути из вершины $$$r$$$ в вершину $$$i$$$.</p><p>После вывода запроса не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul> <li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++; </li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java; </li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal; </li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python; </li><li> смотрите документацию для других языков. </li></ul><p><span class="tex-font-style-bf">Если в какой-то момент вы задали больше, чем $$$\lceil \frac{n}{2} \rceil$$$ вопросов, взаимодействие прекратится, и вы получите вердикт «Неправильный ответ».</span></p><p><span class="tex-font-style-bf">Взломы</span></p><p>Чтобы взломать решение, используйте следующий формат теста.</p><p>Первая строка содержит целое число $$$n$$$ ($$$2 \le n \le 2\,000$$$).</p><p>Следующие $$$n−1$$$ строк содержат два целых числа $$$u$$$ и $$$v$$$ ($$$1 \le u,v \le n$$$), обозначающие ребро между вершинами $$$u$$$ и $$$v$$$ ($$$u \neq v$$$). Эти $$$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 0 1 2 2 1 0 1 1</pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 1 ? 2 ! 4 2 1 2 2 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 2 2 1 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 5 ! 4 5 3 5 2 4 1 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ниже показано дерево из первого примера.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8b00b9d47a8f65effb1b7cd0e2afa71157398819.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Обратите внимание, что ребра можно выводить в любом порядке.</p><p>Кроме того, ниже показаны ответы для всех возможных вопросов в примере $$$1$$$:</p><ul><li> $$$1$$$: $$$[0,1,2,2]$$$ </li><li> $$$2$$$: $$$[1,0,1,1]$$$ </li><li> $$$3$$$: $$$[2,1,0,2]$$$ </li><li> $$$4$$$: $$$[2,1,2,0]$$$</li></ul><p>Ниже показано дерево из второго примера.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/d6cca8f88d77aec46d7fda1dfd0498d1a7b8e07f.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Далее показаны ответы для всех возможных вопросов в примере $$$2$$$:</p><ul><li> $$$1$$$: $$$[0,4,1,3,2]$$$ </li><li> $$$2$$$: $$$[4,0,3,1,2]$$$ </li><li> $$$3$$$: $$$[1,3,0,2,1]$$$ </li><li> $$$4$$$: $$$[3,1,2,0,1]$$$ </li><li> $$$5$$$: $$$[2,2,1,1,0]$$$</li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:28: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:'8124c57b1a7916ec',t:'MTY5NjY2NzMxNC41NDcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*1800"]
1534E
1534
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.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">Это интерактивная задача</span></p><p>XOR-суммой массива $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) называется величина $$$a_1 \oplus a_2 \oplus \ldots \oplus a_n$$$, где $$$\oplus$$$ обозначает операцию <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">побитового исключающего ИЛИ</a>.</p><p>Маленьких Дорми на Рождество получил массив из $$$n$$$ целых $$$a_1, a_2, \ldots, a_n$$$. Однако вскоре он уронил его в XOR-машину, и массив был утерян.</p><p>В настройках XOR-машины установлено целое число $$$k$$$ (которое вы не можете менять), и вы можете делать запросы к XOR-машине: дав машине $$$k$$$ <span class="tex-font-style-bf">различных</span> индексов $$$x_1, x_2, \ldots, x_k$$$, вы получите значение $$$a_{x_1} \oplus a_{x_2} \oplus \ldots \oplus a_{x_k}$$$.</p><p>Как старший брат Дорми, вы хотите помочь ему восстановить <span class="tex-font-style-bf">XOR-сумму</span> массива $$$a_1, a_2, \ldots, a_n$$$, сделав несколько запросов к XOR-машине.</p><p>Маленький Дорми нетерпелив, поэтому вы должны сделать <span class="tex-font-style-bf">минимальное</span> количество запросов к XOR-машине, чтобы найти XOR-сумму массива. Формально, пусть $$$d$$$ равно минимальному числу запросов, необходимому, чтобы найти XOR-сумму любого массива длины $$$n$$$, когда размер запроса равен $$$k$$$. Ваше решение будет зачтено, если вы найдете XOR-сумму за не более чем $$$d$$$ запросов.</p><p>Вы заметили, что для некоторых настроек машины $$$k$$$ и некоторых значений $$$n$$$ может быть невозможно найти XOR-сумму, в таком случае вы должны определить это.</p><p>Массив $$$a_1, a_2, \ldots, a_n$$$ зафиксирован до того, как вы начнете делать запросы к XOR-машине, и не меняется в процессе взаимодействия.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целые числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 500$$$, $$$1 \le k \le n$$$) — длину массива и размер запросов к XOR-машине.</p><p>Элементы массива удовлетворяют $$$1 \le a_i \le 10^9$$$.</p><p>Можно показать, что если возможно найти XOR-сумму в данном тесте, то это можно сделать за не более чем $$$500$$$ запросов. Поэтому $$$d \le 500$$$.</p><p>После чтения $$$n$$$ и $$$k$$$ вы можете начать делать запросы.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если невозможно вычислить XOR-сумму массива, выведите $$$-1$$$ <span class="tex-font-style-bf">сразу</span> после чтения $$$n$$$ и $$$k$$$. Не начинайте взаимодействие.</p><p>Иначе, когда ваша программа определит XOR-сумму найденного массив $$$a_1, a_2, \ldots, a_n$$$, выведите ответ в следующем формате: «<span class="tex-font-style-tt">! x</span>», где $$$x$$$ равен XOR-сумме массива $$$a_1, a_2, \ldots, a_n$$$, и завершите программу сразу после сброса буфера вывода. </p><p>Вывод ответа не считается за запрос.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Чтобы сделать запрос, выведите «<span class="tex-font-style-tt">? b</span>», где $$$b$$$ — массив из ровно $$$k$$$ <span class="tex-font-style-bf">различных</span> целых чисел от $$$1$$$ до $$$n$$$, обозначающий индексы элементов, XOR-сумму которых вы хотите узнать.</p><p>Затем считайте одно целое число $$$x$$$ — XOR-сумму запрошенных элементов. Можно показать, что $$$0 \le x \le 2 \cdot 10^9$$$.</p><p>После вывода запроса не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul> <li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++; </li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java; </li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal; </li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python; </li><li> смотрите документацию для других языков. </li></ul><p><span class="tex-font-style-bf">Если вы сделаете некорректный запрос, или сделаете больше, чем $$$500$$$ запросов, взаимодействие немедленно прекратится и вы получите вердикт «Неправильный ответ». Обратите внимание, если вы превысите $$$d$$$ запросов, взаимодействие продолжится до тех пор, пока вы не превысите лимит в $$$500$$$ запросов, а потом все равно получите вердикт «Неправильный ответ».</span></p><p><span class="tex-font-style-bf">Взломы</span></p><p>Чтобы взломать решение, используйте следующий формат.</p><p>Первая строка содержит целые числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 500$$$, $$$1 \le k \le n$$$).</p><p>Вторая строка содержит массив целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 3 4 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 1 2 3 ? 2 3 5 ? 4 1 5 ! 7 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере массив $$$a_1, a_2, \ldots, a_n$$$ равен $$$2, 1, 7, 5, 6$$$, его XOR-сумма равна $$$7$$$. </p><p>Первый запрос в примере включает индексы $$$1,2,3$$$, поэтому ответ на запрос равен $$$a_1 \oplus a_2 \oplus a_3 = 2 \oplus 1 \oplus 7 = 4$$$.</p><p>Второй запрос в примере включает индексы $$$2,3,5$$$, поэтому ответ на запрос равен $$$a_2 \oplus a_3 \oplus a_5 = 1 \oplus 7 \oplus 6 = 0$$$.</p><p>Первый запрос в примере включает индексы $$$4,1,5$$$, поэтому ответ на запрос равен $$$a_4 \oplus a_1 \oplus a_5 = 5 \oplus 2 \oplus 6 = 1$$$. Обратите внимание, что индексы можно выводить в любом порядке.</p><p>Обратите внимание, что в примере сделано три запроса для демонстрации взаимодействия, но они <span class="tex-font-style-bf">не обязательно</span> следуют оптимальной стратегии.</p><p>Во втором примере невозможно вычислить XOR-сумму массива, поэтому нужно сразу вывести $$$-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="9017cb1c19de3b7dd543ea094439d7b9"/> <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="b150642e1956e0532d7222198d59b78be2e7089e"/> <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='9017cb1c19de3b7dd543ea094439d7b9'>&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=""><a href="/latoken"><img style="height:60px !important;" src="https://latoken.com/_next/static/images/logo-full-dark-fe9406036648016c182d997e0a40986d.svg"/></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%2F1534%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='9017cb1c19de3b7dd543ea094439d7b9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1534">Codeforces LATOKEN Round 1 (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='9017cb1c19de3b7dd543ea094439d7b9'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1534/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='9017cb1c19de3b7dd543ea094439d7b9'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1015233"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='9017cb1c19de3b7dd543ea094439d7b9'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1015233"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91617" title="91617" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13946" resourceName="91617" resourceManual="true" src="//codeforces.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/91760" title="Codeforces LATOKEN Round 1 (Div. 1 + Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13884" resourceName="Codeforces LATOKEN Round 1 (Div. 1 + Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1534">Задачи</a></li> <li><a href="/contest/1534/submit">Отослать</a></li> <li><a href="/contest/1534/my">Мои посылки</a></li> <li><a href="/contest/1534/status">Статус</a></li> <li><a href="/contest/1534/hacks">Взломы</a></li> <li><a href="/contest/1534/room/1">Комната</a></li> <li><a href="/contest/1534/standings">Положение</a></li> <li><a href="/contest/1534/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_5251b3582f3ab6154cfc25c6683c896474b2b6da"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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.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">Это интерактивная задача</span></p><p>XOR-суммой массива $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) называется величина $$$a_1 \oplus a_2 \oplus \ldots \oplus a_n$$$, где $$$\oplus$$$ обозначает операцию <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">побитового исключающего ИЛИ</a>.</p><p>Маленьких Дорми на Рождество получил массив из $$$n$$$ целых $$$a_1, a_2, \ldots, a_n$$$. Однако вскоре он уронил его в XOR-машину, и массив был утерян.</p><p>В настройках XOR-машины установлено целое число $$$k$$$ (которое вы не можете менять), и вы можете делать запросы к XOR-машине: дав машине $$$k$$$ <span class="tex-font-style-bf">различных</span> индексов $$$x_1, x_2, \ldots, x_k$$$, вы получите значение $$$a_{x_1} \oplus a_{x_2} \oplus \ldots \oplus a_{x_k}$$$.</p><p>Как старший брат Дорми, вы хотите помочь ему восстановить <span class="tex-font-style-bf">XOR-сумму</span> массива $$$a_1, a_2, \ldots, a_n$$$, сделав несколько запросов к XOR-машине.</p><p>Маленький Дорми нетерпелив, поэтому вы должны сделать <span class="tex-font-style-bf">минимальное</span> количество запросов к XOR-машине, чтобы найти XOR-сумму массива. Формально, пусть $$$d$$$ равно минимальному числу запросов, необходимому, чтобы найти XOR-сумму любого массива длины $$$n$$$, когда размер запроса равен $$$k$$$. Ваше решение будет зачтено, если вы найдете XOR-сумму за не более чем $$$d$$$ запросов.</p><p>Вы заметили, что для некоторых настроек машины $$$k$$$ и некоторых значений $$$n$$$ может быть невозможно найти XOR-сумму, в таком случае вы должны определить это.</p><p>Массив $$$a_1, a_2, \ldots, a_n$$$ зафиксирован до того, как вы начнете делать запросы к XOR-машине, и не меняется в процессе взаимодействия.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целые числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 500$$$, $$$1 \le k \le n$$$) — длину массива и размер запросов к XOR-машине.</p><p>Элементы массива удовлетворяют $$$1 \le a_i \le 10^9$$$.</p><p>Можно показать, что если возможно найти XOR-сумму в данном тесте, то это можно сделать за не более чем $$$500$$$ запросов. Поэтому $$$d \le 500$$$.</p><p>После чтения $$$n$$$ и $$$k$$$ вы можете начать делать запросы.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если невозможно вычислить XOR-сумму массива, выведите $$$-1$$$ <span class="tex-font-style-bf">сразу</span> после чтения $$$n$$$ и $$$k$$$. Не начинайте взаимодействие.</p><p>Иначе, когда ваша программа определит XOR-сумму найденного массив $$$a_1, a_2, \ldots, a_n$$$, выведите ответ в следующем формате: «<span class="tex-font-style-tt">! x</span>», где $$$x$$$ равен XOR-сумме массива $$$a_1, a_2, \ldots, a_n$$$, и завершите программу сразу после сброса буфера вывода. </p><p>Вывод ответа не считается за запрос.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Чтобы сделать запрос, выведите «<span class="tex-font-style-tt">? b</span>», где $$$b$$$ — массив из ровно $$$k$$$ <span class="tex-font-style-bf">различных</span> целых чисел от $$$1$$$ до $$$n$$$, обозначающий индексы элементов, XOR-сумму которых вы хотите узнать.</p><p>Затем считайте одно целое число $$$x$$$ — XOR-сумму запрошенных элементов. Можно показать, что $$$0 \le x \le 2 \cdot 10^9$$$.</p><p>После вывода запроса не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul> <li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++; </li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java; </li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal; </li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python; </li><li> смотрите документацию для других языков. </li></ul><p><span class="tex-font-style-bf">Если вы сделаете некорректный запрос, или сделаете больше, чем $$$500$$$ запросов, взаимодействие немедленно прекратится и вы получите вердикт «Неправильный ответ». Обратите внимание, если вы превысите $$$d$$$ запросов, взаимодействие продолжится до тех пор, пока вы не превысите лимит в $$$500$$$ запросов, а потом все равно получите вердикт «Неправильный ответ».</span></p><p><span class="tex-font-style-bf">Взломы</span></p><p>Чтобы взломать решение, используйте следующий формат.</p><p>Первая строка содержит целые числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 500$$$, $$$1 \le k \le n$$$).</p><p>Вторая строка содержит массив целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 3 4 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 1 2 3 ? 2 3 5 ? 4 1 5 ! 7 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере массив $$$a_1, a_2, \ldots, a_n$$$ равен $$$2, 1, 7, 5, 6$$$, его XOR-сумма равна $$$7$$$. </p><p>Первый запрос в примере включает индексы $$$1,2,3$$$, поэтому ответ на запрос равен $$$a_1 \oplus a_2 \oplus a_3 = 2 \oplus 1 \oplus 7 = 4$$$.</p><p>Второй запрос в примере включает индексы $$$2,3,5$$$, поэтому ответ на запрос равен $$$a_2 \oplus a_3 \oplus a_5 = 1 \oplus 7 \oplus 6 = 0$$$.</p><p>Первый запрос в примере включает индексы $$$4,1,5$$$, поэтому ответ на запрос равен $$$a_4 \oplus a_1 \oplus a_5 = 5 \oplus 2 \oplus 6 = 1$$$. Обратите внимание, что индексы можно выводить в любом порядке.</p><p>Обратите внимание, что в примере сделано три запроса для демонстрации взаимодействия, но они <span class="tex-font-style-bf">не обязательно</span> следуют оптимальной стратегии.</p><p>Во втором примере невозможно вычислить XOR-сумму массива, поэтому нужно сразу вывести $$$-1$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:28: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:'8124c5839f0b9d34',t:'MTY5NjY2NzMxNS44ODEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\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", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "*2300"]
1534F1
1534
F1
ru
F1. Падающий песок (простая версия)
<div class="problem-statement"><div class="header"><div class="title">F1. Падающий песок (простая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это простая версия задачи. Разница в версиях заключается в ограничениях на $$$a_i$$$. Вы можете делать взломы, только если обе версии задачи решены.</span></p><p>Маленький Дорми недавно получил головоломку от своего друга, и ему требуется ваша помощь для ее решения. </p><p>Головоломка состоит из вертикальной доски с $$$n$$$ строками и $$$m$$$ столбцами, некоторые ячейки на доске пустые, а некоторые заполнены песком. Также даны $$$m$$$ неотрицательных целых чисел $$$a_1,a_2,\ldots,a_m$$$ ($$$0 \leq a_i \leq n$$$). В этой версии задачи $$$a_i$$$ <span class="tex-font-style-bf">равно</span> числу ячеек с песком в столбце $$$i$$$.</p><p>Если стукнуть по ячейке, заполненной песком, то весь песок из ячейки упадет вниз на счетчик песка своего столбца (в каждом столбце есть счетчик песка). Когда песок падает, весь песок, в какой-либо момент находящийся в соседней ячейке с падающим песком, тоже начинает падать. А именно, если песок начинает падать из ячейки $$$(i,j)$$$, то он будет падать через все ячейки ниже в этом столбце, включая саму ячейку $$$(i,j)$$$, вызывая падения во всех ячейках, соседних к какой-либо ячейке на пути. Соседними к ячейке $$$(i,j)$$$ являются ячейки $$$(i-1,j)$$$, $$$(i,j-1)$$$, $$$(i+1,j)$$$ и $$$(i,j+1)$$$ (если такие существуют). Обратите внимание, что новые падающие ячейки песка тоже вызывают падение соседних ячеек.</p><p>За одну операцию вы можете стукнуть по одной ячейке с песком. Головоломка решена, если на счетчике песка в $$$i$$$-м столбце находится <span class="tex-font-style-bf">не менее</span> $$$a_i$$$ ячеек с песком для всех столбцов от $$$1$$$ до $$$m$$$.</p><p>Вам нужно определить минимальное количество операций, необходимое, чтобы решить головоломку. Маленький Дорми никогда не даст вам головоломку, которую нельзя решить.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n \cdot m \leq 400\,000$$$).</p><p>Каждая из следующих $$$n$$$ строк содержит $$$m$$$ символов, описывающих очередную строку таблицы сверху вниз. Символ «<span class="tex-font-style-tt">.</span>» обозначает пустую ячейку, а «<span class="tex-font-style-tt">#</span>» обозначает ячейку с песком.</p><p>Последняя строка содержит $$$m$$$ неотрицательных целых чисел $$$a_1,a_2,\ldots,a_m$$$ ($$$0 \leq a_i \leq n$$$) — минимальное количество ячеек с песком, которые должны упасть на счетчик песка в каждом столбце. В этой версии задачи $$$a_i$$$ всегда <span class="tex-font-style-bf">равно</span> количеству ячеек с песком в столбце $$$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 7 #....#. .#.#... #....#. #....## #.#.... 4 1 1 1 0 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 #.# #.. ##. 3 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере $$$1$$$ можно стукнуть ячейку в левом верхнем углу, ячейку во втором сверху ряду в четвертом столбце слева, и ячейку в третьем ряду сверху в шестом столбце слева. Тогда упадет необходимое количество песка в каждом столбце. Можно показать, что нельзя сделать меньше $$$3$$$ операций, и поэтому ответ равен $$$3$$$. Ниже приведен рисунок к первому примеру.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/6f4f60823652e99e0acbeca4cb8f028e99fb73c0.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center> <p>В примере $$$2$$$ можно стукнуть по ячейке в верхнем ряду в правом столбце, и весь песок в таблице упадет вниз. Поэтому ответ равен $$$1$$$. Ниже приведен рисунок ко второму примеру.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8909639a5d314c829557a36a30624e39447d34f5.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="cadf794b144a4ab94c84753b40308d90"/> <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="b150642e1956e0532d7222198d59b78be2e7089e"/> <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='cadf794b144a4ab94c84753b40308d90'>&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=""><a href="/latoken"><img style="height:60px !important;" src="https://latoken.com/_next/static/images/logo-full-dark-fe9406036648016c182d997e0a40986d.svg"/></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%2F1534%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='cadf794b144a4ab94c84753b40308d90'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1534">Codeforces LATOKEN Round 1 (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='cadf794b144a4ab94c84753b40308d90'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1534/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='cadf794b144a4ab94c84753b40308d90'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1015234"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='cadf794b144a4ab94c84753b40308d90'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1015234"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91617" title="91617" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13946" resourceName="91617" resourceManual="true" src="//codeforces.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/91760" title="Codeforces LATOKEN Round 1 (Div. 1 + Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13884" resourceName="Codeforces LATOKEN Round 1 (Div. 1 + Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1534">Задачи</a></li> <li><a href="/contest/1534/submit">Отослать</a></li> <li><a href="/contest/1534/my">Мои посылки</a></li> <li><a href="/contest/1534/status">Статус</a></li> <li><a href="/contest/1534/hacks">Взломы</a></li> <li><a href="/contest/1534/room/1">Комната</a></li> <li><a href="/contest/1534/standings">Положение</a></li> <li><a href="/contest/1534/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_4af6c6a9a1b7f6fd90ef12f4735160642d452914"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это простая версия задачи. Разница в версиях заключается в ограничениях на $$$a_i$$$. Вы можете делать взломы, только если обе версии задачи решены.</span></p><p>Маленький Дорми недавно получил головоломку от своего друга, и ему требуется ваша помощь для ее решения. </p><p>Головоломка состоит из вертикальной доски с $$$n$$$ строками и $$$m$$$ столбцами, некоторые ячейки на доске пустые, а некоторые заполнены песком. Также даны $$$m$$$ неотрицательных целых чисел $$$a_1,a_2,\ldots,a_m$$$ ($$$0 \leq a_i \leq n$$$). В этой версии задачи $$$a_i$$$ <span class="tex-font-style-bf">равно</span> числу ячеек с песком в столбце $$$i$$$.</p><p>Если стукнуть по ячейке, заполненной песком, то весь песок из ячейки упадет вниз на счетчик песка своего столбца (в каждом столбце есть счетчик песка). Когда песок падает, весь песок, в какой-либо момент находящийся в соседней ячейке с падающим песком, тоже начинает падать. А именно, если песок начинает падать из ячейки $$$(i,j)$$$, то он будет падать через все ячейки ниже в этом столбце, включая саму ячейку $$$(i,j)$$$, вызывая падения во всех ячейках, соседних к какой-либо ячейке на пути. Соседними к ячейке $$$(i,j)$$$ являются ячейки $$$(i-1,j)$$$, $$$(i,j-1)$$$, $$$(i+1,j)$$$ и $$$(i,j+1)$$$ (если такие существуют). Обратите внимание, что новые падающие ячейки песка тоже вызывают падение соседних ячеек.</p><p>За одну операцию вы можете стукнуть по одной ячейке с песком. Головоломка решена, если на счетчике песка в $$$i$$$-м столбце находится <span class="tex-font-style-bf">не менее</span> $$$a_i$$$ ячеек с песком для всех столбцов от $$$1$$$ до $$$m$$$.</p><p>Вам нужно определить минимальное количество операций, необходимое, чтобы решить головоломку. Маленький Дорми никогда не даст вам головоломку, которую нельзя решить.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n \cdot m \leq 400\,000$$$).</p><p>Каждая из следующих $$$n$$$ строк содержит $$$m$$$ символов, описывающих очередную строку таблицы сверху вниз. Символ «<span class="tex-font-style-tt">.</span>» обозначает пустую ячейку, а «<span class="tex-font-style-tt">#</span>» обозначает ячейку с песком.</p><p>Последняя строка содержит $$$m$$$ неотрицательных целых чисел $$$a_1,a_2,\ldots,a_m$$$ ($$$0 \leq a_i \leq n$$$) — минимальное количество ячеек с песком, которые должны упасть на счетчик песка в каждом столбце. В этой версии задачи $$$a_i$$$ всегда <span class="tex-font-style-bf">равно</span> количеству ячеек с песком в столбце $$$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 7 #....#. .#.#... #....#. #....## #.#.... 4 1 1 1 0 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 #.# #.. ##. 3 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере $$$1$$$ можно стукнуть ячейку в левом верхнем углу, ячейку во втором сверху ряду в четвертом столбце слева, и ячейку в третьем ряду сверху в шестом столбце слева. Тогда упадет необходимое количество песка в каждом столбце. Можно показать, что нельзя сделать меньше $$$3$$$ операций, и поэтому ответ равен $$$3$$$. Ниже приведен рисунок к первому примеру.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/6f4f60823652e99e0acbeca4cb8f028e99fb73c0.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center> <p>В примере $$$2$$$ можно стукнуть по ячейке в верхнем ряду в правом столбце, и весь песок в таблице упадет вниз. Поэтому ответ равен $$$1$$$. Ниже приведен рисунок ко второму примеру.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8909639a5d314c829557a36a30624e39447d34f5.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center> </div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F1]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:28: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:'8124c58bfd9a7b77',t:'MTY5NjY2NzMxNy4yMjcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "*2500"]
1534F2
1534
F2
ru
F2. Падающий песок (сложная версия)
<div class="problem-statement"><div class="header"><div class="title">F2. Падающий песок (сложная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это сложная версия задачи. Разница в версиях заключается в ограничениях на $$$a_i$$$. Вы можете делать взломы, только если обе версии задачи решены.</span></p><p>Маленький Дорми недавно получил головоломку от своего друга, и ему требуется ваша помощь для ее решения. </p><p>Головоломка состоит из вертикальной доски с $$$n$$$ строками и $$$m$$$ столбцами, некоторые ячейки на доске пустые, а некоторые заполнены песком. Также даны $$$m$$$ неотрицательных целых чисел $$$a_1,a_2,\ldots,a_m$$$ ($$$0 \leq a_i \leq n$$$). В этой версии задачи $$$a_i$$$ всегда <span class="tex-font-style-bf">не превышает</span> количества ячеек с песком в столбце $$$i$$$.</p><p>Если стукнуть по ячейке, заполненной песком, то весь песок из ячейки упадет вниз на счетчик песка своего столбца (в каждом столбце есть счетчик песка). Когда песок падает, весь песок, в какой-либо момент находящийся в соседней ячейке с падающим песком, тоже начинает падать. А именно, если песок начинает падать из ячейки $$$(i,j)$$$, то он будет падать через все ячейки ниже в этом столбце, включая саму ячейку $$$(i,j)$$$, вызывая падения во всех ячейках, соседних к какой-либо ячейке на пути. Соседними к ячейке $$$(i,j)$$$ являются ячейки $$$(i-1,j)$$$, $$$(i,j-1)$$$, $$$(i+1,j)$$$ и $$$(i,j+1)$$$ (если такие существуют). Обратите внимание, что новые падающие ячейки песка тоже вызывают падение соседних ячеек.</p><p>За одну операцию вы можете стукнуть по одной ячейке с песком. Головоломка решена, если на счетчике песка в $$$i$$$-м столбце находится <span class="tex-font-style-bf">не менее</span> $$$a_i$$$ ячеек с песком для всех столбцов от $$$1$$$ до $$$m$$$.</p><p>Вам нужно определить минимальное количество операций, необходимое, чтобы решить головоломку, или сказать, что это невозможно. Маленький Дорми никогда не даст вам головоломку, которую нельзя решить.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n \cdot m \leq 400\,000$$$).</p><p>Каждая из следующих $$$n$$$ строк содержит $$$m$$$ символов, описывающих очередную строку таблицы сверху вниз. Символ «<span class="tex-font-style-tt">.</span>» обозначает пустую ячейку, а «<span class="tex-font-style-tt">#</span>» обозначает ячейку с песком.</p><p>Последняя строка содержит $$$m$$$ неотрицательных целых чисел $$$a_1,a_2,\ldots,a_m$$$ ($$$0 \leq a_i \leq n$$$) — минимальное количество ячеек с песком, которые должны упасть на счетчик песка в каждом столбце. В этой версии задачи $$$a_i$$$ всегда <span class="tex-font-style-bf">не превышает</span> количества ячеек с песком в столбце $$$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 7 #....#. .#.#... #....#. #....## #.#.... 4 1 1 1 0 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 #.# #.. ##. 3 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 5 .#..# #.... ..##. ..##. ..### ..#.. #.##. 0 0 2 4 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере $$$1$$$ можно стукнуть по ячейке в левом верхнем углу, и по ячейке в третьей строке сверху в шестом столбце слева. Тогда на счетчики песка упадет необходимый объем песка в каждом столбце. Можно показать, что нельзя решить головоломку менее чем за $$$3$$$ операции, и поэтому ответ равен $$$3$$$. Ниже приведен рисунок к первому примеру.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/2c31781e443be3f95ceba749fbf1aee398b2d30e.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center> <p>В примере $$$2$$$ можно стукнуть по ячейке в верхнем ряду в правом столбце, и весь песок в таблице упадет вниз. Поэтому ответ равен $$$1$$$. Ниже приведен рисунок ко второму примеру.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8909639a5d314c829557a36a30624e39447d34f5.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center> <p>В примере $$$3$$$ можно стукнуть по ячейке в верхнем ряду в правом столбце, и в каждом столбце упадет достаточно песка. Можно показать, что невозможно решить головоломку за менее, чем $$$1$$$ операцию, поэтому ответ $$$1$$$. Ниже приведен рисунок ко второму примеру.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/fd9f79d797ebd73df689ba1fdb5621a58fdb2d09.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="78cdcb2d0f5aa0c63454fa69b210af5d"/> <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="b150642e1956e0532d7222198d59b78be2e7089e"/> <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='78cdcb2d0f5aa0c63454fa69b210af5d'>&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=""><a href="/latoken"><img style="height:60px !important;" src="https://latoken.com/_next/static/images/logo-full-dark-fe9406036648016c182d997e0a40986d.svg"/></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%2F1534%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='78cdcb2d0f5aa0c63454fa69b210af5d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1534">Codeforces LATOKEN Round 1 (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='78cdcb2d0f5aa0c63454fa69b210af5d'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1534/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='78cdcb2d0f5aa0c63454fa69b210af5d'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1015235"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='78cdcb2d0f5aa0c63454fa69b210af5d'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1015235"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91617" title="91617" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13946" resourceName="91617" resourceManual="true" src="//codeforces.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/91760" title="Codeforces LATOKEN Round 1 (Div. 1 + Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13884" resourceName="Codeforces LATOKEN Round 1 (Div. 1 + Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1534">Задачи</a></li> <li><a href="/contest/1534/submit">Отослать</a></li> <li><a href="/contest/1534/my">Мои посылки</a></li> <li><a href="/contest/1534/status">Статус</a></li> <li><a href="/contest/1534/hacks">Взломы</a></li> <li><a href="/contest/1534/room/1">Комната</a></li> <li><a href="/contest/1534/standings">Положение</a></li> <li><a href="/contest/1534/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_ac90581f5da596e2fe88d54c7ff1a1a7611546ef"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это сложная версия задачи. Разница в версиях заключается в ограничениях на $$$a_i$$$. Вы можете делать взломы, только если обе версии задачи решены.</span></p><p>Маленький Дорми недавно получил головоломку от своего друга, и ему требуется ваша помощь для ее решения. </p><p>Головоломка состоит из вертикальной доски с $$$n$$$ строками и $$$m$$$ столбцами, некоторые ячейки на доске пустые, а некоторые заполнены песком. Также даны $$$m$$$ неотрицательных целых чисел $$$a_1,a_2,\ldots,a_m$$$ ($$$0 \leq a_i \leq n$$$). В этой версии задачи $$$a_i$$$ всегда <span class="tex-font-style-bf">не превышает</span> количества ячеек с песком в столбце $$$i$$$.</p><p>Если стукнуть по ячейке, заполненной песком, то весь песок из ячейки упадет вниз на счетчик песка своего столбца (в каждом столбце есть счетчик песка). Когда песок падает, весь песок, в какой-либо момент находящийся в соседней ячейке с падающим песком, тоже начинает падать. А именно, если песок начинает падать из ячейки $$$(i,j)$$$, то он будет падать через все ячейки ниже в этом столбце, включая саму ячейку $$$(i,j)$$$, вызывая падения во всех ячейках, соседних к какой-либо ячейке на пути. Соседними к ячейке $$$(i,j)$$$ являются ячейки $$$(i-1,j)$$$, $$$(i,j-1)$$$, $$$(i+1,j)$$$ и $$$(i,j+1)$$$ (если такие существуют). Обратите внимание, что новые падающие ячейки песка тоже вызывают падение соседних ячеек.</p><p>За одну операцию вы можете стукнуть по одной ячейке с песком. Головоломка решена, если на счетчике песка в $$$i$$$-м столбце находится <span class="tex-font-style-bf">не менее</span> $$$a_i$$$ ячеек с песком для всех столбцов от $$$1$$$ до $$$m$$$.</p><p>Вам нужно определить минимальное количество операций, необходимое, чтобы решить головоломку, или сказать, что это невозможно. Маленький Дорми никогда не даст вам головоломку, которую нельзя решить.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n \cdot m \leq 400\,000$$$).</p><p>Каждая из следующих $$$n$$$ строк содержит $$$m$$$ символов, описывающих очередную строку таблицы сверху вниз. Символ «<span class="tex-font-style-tt">.</span>» обозначает пустую ячейку, а «<span class="tex-font-style-tt">#</span>» обозначает ячейку с песком.</p><p>Последняя строка содержит $$$m$$$ неотрицательных целых чисел $$$a_1,a_2,\ldots,a_m$$$ ($$$0 \leq a_i \leq n$$$) — минимальное количество ячеек с песком, которые должны упасть на счетчик песка в каждом столбце. В этой версии задачи $$$a_i$$$ всегда <span class="tex-font-style-bf">не превышает</span> количества ячеек с песком в столбце $$$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 7 #....#. .#.#... #....#. #....## #.#.... 4 1 1 1 0 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 #.# #.. ##. 3 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 5 .#..# #.... ..##. ..##. ..### ..#.. #.##. 0 0 2 4 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере $$$1$$$ можно стукнуть по ячейке в левом верхнем углу, и по ячейке в третьей строке сверху в шестом столбце слева. Тогда на счетчики песка упадет необходимый объем песка в каждом столбце. Можно показать, что нельзя решить головоломку менее чем за $$$3$$$ операции, и поэтому ответ равен $$$3$$$. Ниже приведен рисунок к первому примеру.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/2c31781e443be3f95ceba749fbf1aee398b2d30e.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center> <p>В примере $$$2$$$ можно стукнуть по ячейке в верхнем ряду в правом столбце, и весь песок в таблице упадет вниз. Поэтому ответ равен $$$1$$$. Ниже приведен рисунок ко второму примеру.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8909639a5d314c829557a36a30624e39447d34f5.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center> <p>В примере $$$3$$$ можно стукнуть по ячейке в верхнем ряду в правом столбце, и в каждом столбце упадет достаточно песка. Можно показать, что невозможно решить головоломку за менее, чем $$$1$$$ операцию, поэтому ответ $$$1$$$. Ниже приведен рисунок ко второму примеру.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/fd9f79d797ebd73df689ba1fdb5621a58fdb2d09.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=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 11:28: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:'8124c5947a687a75',t:'MTY5NjY2NzMxOC41OTEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*3000"]
1534G
1534
G
ru
G. Новое начало
<div class="problem-statement"><div class="header"><div class="title">G. Новое начало</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Анни устала выигрывать все контесты и получать бесконечный рейтинг, поэтому сегодня вместо контеста она поехала сажать картошку.</p><p>Участок Анни можно представить в виде бесконечной плоскости. Анни должна посадить $$$n$$$ кустов картошки, $$$i$$$-й куст должен быть посажен в точке $$$(x_i,y_i)$$$. Анни начнет в точке $$$(0, 0)$$$, и за один шаг будет перемещаться на одну единицу длины <span class="tex-font-style-bf">вправо</span> или <span class="tex-font-style-bf">вверх</span> (т. е. увеличивать свою координату $$$x$$$ или $$$y$$$ на $$$1$$$). Из любой точки $$$(X,Y)$$$ в процессе движения она может посадить любое количество кустов в любых точках плоскости, используя свою картофельную пушку. Для посадки одного куста в точку $$$(x,y)$$$ требуется $$$\max(|X-x|,|Y-y|)$$$ единиц энергии. Найдите минимальное количество энергии, необходимое для посадки всех кустов картошки.</p><p>Обратите внимание, что Анни может посадить любое количество кустов из любой точки.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 800\,000$$$).</p><p>Следующие $$$n$$$ строк содержат по два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$0 \le x_i,y_i \le 10^9$$$), определяющие требуемое положение $$$i$$$-го куста картошки. Возможно, некоторые кусты картошки требуется посадить в одно и то же место.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите минимальное количество энергии, необходимое для посадки всей картошки.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 1 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 1 2 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 5 5 7 7 4 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 5 1 4 0 9 6 0 2 10 1 9 10 3 10 0 10 8 9 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 19 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 1 1 2 2 2 0 4 2 4 0 2 0 0 2 4 0 4 2 5 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере $$$1$$$ Анни может посетить все необходимые точки, поэтому энергия не требуется.</p><p>В примере $$$2$$$ Анни сначала может пойти в $$$(1,0)$$$, посадить оттуда второй куст, используя $$$1$$$ единицу энергии. Затем она пойдет в $$$(1,1)$$$ и посадит первый куст, используя $$$0$$$ единиц энергии.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="6c82261fe4bc95ab77adc85efedef776"/> <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="b150642e1956e0532d7222198d59b78be2e7089e"/> <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='6c82261fe4bc95ab77adc85efedef776'>&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=""><a href="/latoken"><img style="height:60px !important;" src="https://latoken.com/_next/static/images/logo-full-dark-fe9406036648016c182d997e0a40986d.svg"/></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%2F1534%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='6c82261fe4bc95ab77adc85efedef776'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1534">Codeforces LATOKEN Round 1 (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='6c82261fe4bc95ab77adc85efedef776'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1534/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='6c82261fe4bc95ab77adc85efedef776'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1015236"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6c82261fe4bc95ab77adc85efedef776'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1015236"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91617" title="91617" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13946" resourceName="91617" resourceManual="true" src="//codeforces.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/91760" title="Codeforces LATOKEN Round 1 (Div. 1 + Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13884" resourceName="Codeforces LATOKEN Round 1 (Div. 1 + Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1534">Задачи</a></li> <li><a href="/contest/1534/submit">Отослать</a></li> <li><a href="/contest/1534/my">Мои посылки</a></li> <li><a href="/contest/1534/status">Статус</a></li> <li><a href="/contest/1534/hacks">Взломы</a></li> <li><a href="/contest/1534/room/1">Комната</a></li> <li><a href="/contest/1534/standings">Положение</a></li> <li><a href="/contest/1534/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_250041b9f1e45215035efd5da68c8eeb955dcc07"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">G. Новое начало</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Анни устала выигрывать все контесты и получать бесконечный рейтинг, поэтому сегодня вместо контеста она поехала сажать картошку.</p><p>Участок Анни можно представить в виде бесконечной плоскости. Анни должна посадить $$$n$$$ кустов картошки, $$$i$$$-й куст должен быть посажен в точке $$$(x_i,y_i)$$$. Анни начнет в точке $$$(0, 0)$$$, и за один шаг будет перемещаться на одну единицу длины <span class="tex-font-style-bf">вправо</span> или <span class="tex-font-style-bf">вверх</span> (т. е. увеличивать свою координату $$$x$$$ или $$$y$$$ на $$$1$$$). Из любой точки $$$(X,Y)$$$ в процессе движения она может посадить любое количество кустов в любых точках плоскости, используя свою картофельную пушку. Для посадки одного куста в точку $$$(x,y)$$$ требуется $$$\max(|X-x|,|Y-y|)$$$ единиц энергии. Найдите минимальное количество энергии, необходимое для посадки всех кустов картошки.</p><p>Обратите внимание, что Анни может посадить любое количество кустов из любой точки.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 800\,000$$$).</p><p>Следующие $$$n$$$ строк содержат по два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$0 \le x_i,y_i \le 10^9$$$), определяющие требуемое положение $$$i$$$-го куста картошки. Возможно, некоторые кусты картошки требуется посадить в одно и то же место.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите минимальное количество энергии, необходимое для посадки всей картошки.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 1 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 1 2 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 5 5 7 7 4 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 5 1 4 0 9 6 0 2 10 1 9 10 3 10 0 10 8 9 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 19 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 1 1 2 2 2 0 4 2 4 0 2 0 0 2 4 0 4 2 5 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере $$$1$$$ Анни может посетить все необходимые точки, поэтому энергия не требуется.</p><p>В примере $$$2$$$ Анни сначала может пойти в $$$(1,0)$$$, посадить оттуда второй куст, используя $$$1$$$ единицу энергии. Затем она пойдет в $$$(1,1)$$$ и посадит первый куст, используя $$$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 11:28: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:'8124c59cce1416d3',t:'MTY5NjY2NzMxOS45OTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u0434\u043f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3300"]
1534H
1534
H
ru
H. Потерянные вершины
<div class="problem-statement"><div class="header"><div class="title">H. Потерянные вершины</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это интерактивная задача.</span></p><p>Так как маленький Эрики прошел на Международную олимпиаду школьников по информатике в этом году, он получил подарок от своих друзей: дерево с $$$n$$$ вершинами!</p><p>По пути к месту проведения Эрики было скучно, поэтому он решил сыграть в игру с маленьким Ивонном с использованием нового дерева. Сначала Ивонн загадывает две (не обязательно различные) вершины $$$a$$$ и $$$b$$$ в этом дереве (не сообщая их Эрики), а затем сообщает ему подсказку $$$f$$$ — одну из вершин на простом пути от $$$a$$$ до $$$b$$$.</p><p>Затем маленький Эрики может спрашивать следующие вопросы:</p><ul><li> Если подвесить дерево за вершину $$$r$$$ (Эрики может выбрать $$$r$$$), какая вершина будет <a href="https://ru.wikipedia.org/wiki/Наименьший_общий_предок">наименьшим общим предком</a> вершин $$$a$$$ и $$$b$$$?</li></ul><p>Задача маленького Эрики — найти вершины $$$a$$$ и $$$b$$$.</p><p>Маленький Ивонн считает игру слишком простой, поэтому в начале игры, перед тем, как дать подсказку $$$f$$$, он просит Эрики найти максимальное количество запросов, необходимых для нахождения $$$a$$$ и $$$b$$$ для всех возможных значений $$$a$$$, $$$b$$$ и $$$f$$$ в предположении, что Эрики действует оптимально. Под оптимальными действиями подразумевается стратегия, делающая наименьшее число запросов. Конечно, после того, как маленький Эрики скажет это максимальное количество запросов, Ивонн не разрешит сделать больше запросов в самой игре.</p><p>Дерево, $$$a$$$, $$$b$$$ и $$$f$$$ фиксированы до начала игры и не меняются в зависимости от запросов.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Сначала считайте строку, содержащую одно целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — количество вершин в дереве.</p><p>Сделающие $$$n−1$$$ строк описывают дерево маленького Дорми. Каждая из этих строк содержит два целых числа $$$u$$$ и $$$v$$$ ($$$1 \le u,v \le n$$$), обозначающие ребро между вершинами $$$u$$$ и $$$v$$$ ($$$u \neq v$$$). Гарантируется, что эти ребра образуют дерево.</p><p>После этого вы должны вывести $$$k$$$ — максимальное число запросов, необходимое для определения $$$a$$$ и $$$b$$$ по всем возможным значениям $$$a$$$, $$$b$$$ и $$$f$$$ в предположении оптимальной игры. Вы должны вывести перевод строки и сбросить буфер вывода после вывода $$$k$$$.</p><p>Затем считайте одно целое число $$$f$$$ ($$$1 \le f \le n$$$) — подсказку: вершину на пути от $$$a$$$ до $$$b$$$ включительно.</p><p>После этого вы можете делать запросы. Вам будет разрешено сделать не более $$$k$$$ запросов, где $$$k$$$ — число, которое вы вывели.</p><p>Для того, чтобы сделать запрос, выведите «<span class="tex-font-style-tt">? r</span>», где $$$r$$$ — целое число, $$$1 \le r \le n$$$, обозначающее, за какую вершину вы хотите подвесить дерево.</p><p>В ответ вы получите целое число $$$x$$$ ($$$1 \le x \le n$$$) — наименьший общий предок вершин $$$a$$$ и $$$b$$$, если дерево подвесить за $$$r$$$.</p><p>Когда ваша программа определит $$$a$$$ и $$$b$$$, выведите их в следующем формате: «<span class="tex-font-style-tt">! a b</span>», где $$$a$$$ и $$$b$$$ — две загаданные вершины, и завершите программу сразу после сброса буфера вывода. Вы можете вывести $$$a$$$ и $$$b$$$ в любом порядке.</p><p>После вывода запроса не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul> <li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++; </li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java; </li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal; </li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python; </li><li> смотрите документацию для других языков. </li></ul><p><span class="tex-font-style-bf">Если вы сделаете некорректный вывод, или сделаете более $$$k$$$ запросов, взаимодействие прекратится и вы получите вердикт «Неправильный ответ». Вывод считается некорректным, если это некорректный запрос, или вы вывели $$$k$$$, меньшее $$$0$$$ или большее $$$n$$$.</span></p><p><span class="tex-font-style-bf">Взломы</span></p><p>Чтобы взломать решение, используйте следующий формат:</p><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^5$$$).</p><p>Следующие $$$n−1$$$ строк содержат по два целых числа $$$u$$$ и $$$v$$$ ($$$1 \le u,v \le n$$$), обозначающие ребро между вершинами $$$u$$$ и $$$v$$$ ($$$u \neq v$$$). Эти $$$n-1$$$ ребра должны образовывать дерево.</p><p>Следующая строка содержит два целых числа $$$a$$$ и $$$b$$$ ($$$1 \le a,b \le n$$$).</p><p>Последняя строка должна содержать одно целое число $$$f$$$ ($$$1 \le f \le n$$$). Вершина $$$f$$$ должна лежать на простом пути от $$$a$$$ до $$$b$$$ включительно.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 2 1 2 4 1 1 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 ? 1 ? 2 ? 3 ! 4 1</pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 1 1 4 4 5 4 2 1 4 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 ? 4 ? 1 ? 5 ! 1 4</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Дерево из первого примера показано ниже. Вершины $$$a$$$ и $$$b$$$ выделены жирным.</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/5b0b6dc78b10d9ec52afe52f9985dfd139874a00.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Обратите внимание, что вы можете вывести $$$a$$$ и $$$b$$$ в любом порядке.</p><p>Ниже приведены ответы на все возможные запросы $$$1,2,\ldots,n$$$:</p><ul><li> $$$1$$$: $$$1$$$ </li><li> $$$2$$$: $$$2$$$ </li><li> $$$3$$$: $$$2$$$ </li><li> $$$4$$$: $$$4$$$</li></ul><p>__________________________________________</p><p>Дерево из второго примера показано ниже. Вершины $$$a$$$ и $$$b$$$ выделены жирным.</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/f2819e4480c58243a49beaa5d2d5db30a781d445.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Ниже приведены ответы на все возможные запросы $$$1,2,\ldots,n$$$ в примере $$$2$$$:</p><ul><li> $$$1$$$: $$$1$$$ </li><li> $$$2$$$: $$$4$$$ </li><li> $$$3$$$: $$$1$$$ </li><li> $$$4$$$: $$$4$$$ </li><li> $$$5$$$: $$$4$$$</li></ul></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="f5f6059b2cd6fb194994e87972619274"/> <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="b150642e1956e0532d7222198d59b78be2e7089e"/> <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='f5f6059b2cd6fb194994e87972619274'>&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=""><a href="/latoken"><img style="height:60px !important;" src="https://latoken.com/_next/static/images/logo-full-dark-fe9406036648016c182d997e0a40986d.svg"/></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%2F1534%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='f5f6059b2cd6fb194994e87972619274'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1534">Codeforces LATOKEN Round 1 (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='f5f6059b2cd6fb194994e87972619274'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1534/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *3500 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f5f6059b2cd6fb194994e87972619274'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1015237"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f5f6059b2cd6fb194994e87972619274'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1015237"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91617" title="91617" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13946" resourceName="91617" resourceManual="true" src="//codeforces.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/91760" title="Codeforces LATOKEN Round 1 (Div. 1 + Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13884" resourceName="Codeforces LATOKEN Round 1 (Div. 1 + Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1534">Задачи</a></li> <li><a href="/contest/1534/submit">Отослать</a></li> <li><a href="/contest/1534/my">Мои посылки</a></li> <li><a href="/contest/1534/status">Статус</a></li> <li><a href="/contest/1534/hacks">Взломы</a></li> <li><a href="/contest/1534/room/1">Комната</a></li> <li><a href="/contest/1534/standings">Положение</a></li> <li><a href="/contest/1534/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_3c24730657d423be9d47bfe59510761567f6e423"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это интерактивная задача.</span></p><p>Так как маленький Эрики прошел на Международную олимпиаду школьников по информатике в этом году, он получил подарок от своих друзей: дерево с $$$n$$$ вершинами!</p><p>По пути к месту проведения Эрики было скучно, поэтому он решил сыграть в игру с маленьким Ивонном с использованием нового дерева. Сначала Ивонн загадывает две (не обязательно различные) вершины $$$a$$$ и $$$b$$$ в этом дереве (не сообщая их Эрики), а затем сообщает ему подсказку $$$f$$$ — одну из вершин на простом пути от $$$a$$$ до $$$b$$$.</p><p>Затем маленький Эрики может спрашивать следующие вопросы:</p><ul><li> Если подвесить дерево за вершину $$$r$$$ (Эрики может выбрать $$$r$$$), какая вершина будет <a href="https://ru.wikipedia.org/wiki/Наименьший_общий_предок">наименьшим общим предком</a> вершин $$$a$$$ и $$$b$$$?</li></ul><p>Задача маленького Эрики — найти вершины $$$a$$$ и $$$b$$$.</p><p>Маленький Ивонн считает игру слишком простой, поэтому в начале игры, перед тем, как дать подсказку $$$f$$$, он просит Эрики найти максимальное количество запросов, необходимых для нахождения $$$a$$$ и $$$b$$$ для всех возможных значений $$$a$$$, $$$b$$$ и $$$f$$$ в предположении, что Эрики действует оптимально. Под оптимальными действиями подразумевается стратегия, делающая наименьшее число запросов. Конечно, после того, как маленький Эрики скажет это максимальное количество запросов, Ивонн не разрешит сделать больше запросов в самой игре.</p><p>Дерево, $$$a$$$, $$$b$$$ и $$$f$$$ фиксированы до начала игры и не меняются в зависимости от запросов.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Сначала считайте строку, содержащую одно целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — количество вершин в дереве.</p><p>Сделающие $$$n−1$$$ строк описывают дерево маленького Дорми. Каждая из этих строк содержит два целых числа $$$u$$$ и $$$v$$$ ($$$1 \le u,v \le n$$$), обозначающие ребро между вершинами $$$u$$$ и $$$v$$$ ($$$u \neq v$$$). Гарантируется, что эти ребра образуют дерево.</p><p>После этого вы должны вывести $$$k$$$ — максимальное число запросов, необходимое для определения $$$a$$$ и $$$b$$$ по всем возможным значениям $$$a$$$, $$$b$$$ и $$$f$$$ в предположении оптимальной игры. Вы должны вывести перевод строки и сбросить буфер вывода после вывода $$$k$$$.</p><p>Затем считайте одно целое число $$$f$$$ ($$$1 \le f \le n$$$) — подсказку: вершину на пути от $$$a$$$ до $$$b$$$ включительно.</p><p>После этого вы можете делать запросы. Вам будет разрешено сделать не более $$$k$$$ запросов, где $$$k$$$ — число, которое вы вывели.</p><p>Для того, чтобы сделать запрос, выведите «<span class="tex-font-style-tt">? r</span>», где $$$r$$$ — целое число, $$$1 \le r \le n$$$, обозначающее, за какую вершину вы хотите подвесить дерево.</p><p>В ответ вы получите целое число $$$x$$$ ($$$1 \le x \le n$$$) — наименьший общий предок вершин $$$a$$$ и $$$b$$$, если дерево подвесить за $$$r$$$.</p><p>Когда ваша программа определит $$$a$$$ и $$$b$$$, выведите их в следующем формате: «<span class="tex-font-style-tt">! a b</span>», где $$$a$$$ и $$$b$$$ — две загаданные вершины, и завершите программу сразу после сброса буфера вывода. Вы можете вывести $$$a$$$ и $$$b$$$ в любом порядке.</p><p>После вывода запроса не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul> <li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++; </li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java; </li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal; </li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python; </li><li> смотрите документацию для других языков. </li></ul><p><span class="tex-font-style-bf">Если вы сделаете некорректный вывод, или сделаете более $$$k$$$ запросов, взаимодействие прекратится и вы получите вердикт «Неправильный ответ». Вывод считается некорректным, если это некорректный запрос, или вы вывели $$$k$$$, меньшее $$$0$$$ или большее $$$n$$$.</span></p><p><span class="tex-font-style-bf">Взломы</span></p><p>Чтобы взломать решение, используйте следующий формат:</p><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^5$$$).</p><p>Следующие $$$n−1$$$ строк содержат по два целых числа $$$u$$$ и $$$v$$$ ($$$1 \le u,v \le n$$$), обозначающие ребро между вершинами $$$u$$$ и $$$v$$$ ($$$u \neq v$$$). Эти $$$n-1$$$ ребра должны образовывать дерево.</p><p>Следующая строка содержит два целых числа $$$a$$$ и $$$b$$$ ($$$1 \le a,b \le n$$$).</p><p>Последняя строка должна содержать одно целое число $$$f$$$ ($$$1 \le f \le n$$$). Вершина $$$f$$$ должна лежать на простом пути от $$$a$$$ до $$$b$$$ включительно.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 2 1 2 4 1 1 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 ? 1 ? 2 ? 3 ! 4 1</pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 1 1 4 4 5 4 2 1 4 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 ? 4 ? 1 ? 5 ! 1 4</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Дерево из первого примера показано ниже. Вершины $$$a$$$ и $$$b$$$ выделены жирным.</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/5b0b6dc78b10d9ec52afe52f9985dfd139874a00.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Обратите внимание, что вы можете вывести $$$a$$$ и $$$b$$$ в любом порядке.</p><p>Ниже приведены ответы на все возможные запросы $$$1,2,\ldots,n$$$:</p><ul><li> $$$1$$$: $$$1$$$ </li><li> $$$2$$$: $$$2$$$ </li><li> $$$3$$$: $$$2$$$ </li><li> $$$4$$$: $$$4$$$</li></ul><p>__________________________________________</p><p>Дерево из второго примера показано ниже. Вершины $$$a$$$ и $$$b$$$ выделены жирным.</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/f2819e4480c58243a49beaa5d2d5db30a781d445.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Ниже приведены ответы на все возможные запросы $$$1,2,\ldots,n$$$ в примере $$$2$$$:</p><ul><li> $$$1$$$: $$$1$$$ </li><li> $$$2$$$: $$$4$$$ </li><li> $$$3$$$: $$$1$$$ </li><li> $$$4$$$: $$$4$$$ </li><li> $$$5$$$: $$$4$$$</li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=H]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:28: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:'8124c5a5bd051411',t:'MTY5NjY2NzMyMS4zMzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\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", "\u0434\u043f", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*3500"]
1535A
1535
A
ru
A. Честный плей-офф
<div class="problem-statement"><div class="header"><div class="title">A. Честный плей-офф</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В турнире по системе плей-офф участвуют четыре игрока. Турнир проводится по следующей схеме: первый игрок сыграет со вторым, а третий с четвертым, затем победители пар сыграют в финале турнира. </p><p>Известно, что в матче между двумя игроками выиграет тот, чье мастерство больше. Мастерство $$$i$$$-го игрока равно $$$s_i$$$ и все уровни мастерства попарно различны (т.е. в массиве $$$s$$$ нет двух одинаковых значений).</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 10^4$$$) — количество наборов входных данных. </p><p>Единственная строка входных данных содержит четыре целых числа $$$s_1, s_2, s_3, s_4$$$ ($$$1 \le s_i \le 100$$$) — мастерство игроков. Гарантируется, что в массиве все числа различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите <span class="tex-font-style-tt">YES</span>, если турнир является <span class="tex-font-style-bf">честным</span>, или <span class="tex-font-style-tt">NO</span> в противном случае.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 7 9 5 4 5 6 9 5 3 8 1 6 5 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES NO YES NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим примеры:</p><ol> <li> в первом примере игроки $$$2$$$ и $$$3$$$ с навыками $$$7$$$ и $$$9$$$ выходят в финал; </li><li> во втором примере игроки $$$2$$$ и $$$4$$$ с навыками $$$5$$$ и $$$9$$$ выходят в финал. Игрок с навыком $$$6$$$ не прошел в финал, но игрок с навыком $$$5$$$ прошел в финал, поэтому турнир нечестен; </li><li> в третьем примере игроки $$$1$$$ и $$$3$$$ с навыками $$$5$$$ и $$$8$$$ выходят в финал; </li><li> в четвертом примере игроки $$$1$$$ и $$$3$$$ с навыками $$$6$$$ и $$$3$$$ выходят в финал. Игрок с навыком $$$5$$$ не прошел в финал, но игрок с навыком $$$3$$$ прошел в финал, поэтому турнир нечестен. </li></ol></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="c46b0153df92d4c9856ca88712bfe8fd"/> <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="60b218a6c3a91fe751ac8150ebad932bcdaef025"/> <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='c46b0153df92d4c9856ca88712bfe8fd'>&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%2F1535%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='c46b0153df92d4c9856ca88712bfe8fd'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1535">Educational Codeforces Round 110 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left 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='c46b0153df92d4c9856ca88712bfe8fd'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1535/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *800 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c46b0153df92d4c9856ca88712bfe8fd'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1005282"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c46b0153df92d4c9856ca88712bfe8fd'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1005282"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91386" title="Educational Codeforces Round 110 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13808:13809" 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/91481" title="91481" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13829:13830" 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/1535">Задачи</a></li> <li><a href="/contest/1535/submit">Отослать</a></li> <li><a href="/contest/1535/my">Мои посылки</a></li> <li><a href="/contest/1535/status">Статус</a></li> <li><a href="/contest/1535/hacks">Взломы</a></li> <li><a href="/contest/1535/standings">Положение</a></li> <li><a href="/contest/1535/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0ed8d77fc5c53f94ee584da756666b3b9b97a86c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Честный плей-офф</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В турнире по системе плей-офф участвуют четыре игрока. Турнир проводится по следующей схеме: первый игрок сыграет со вторым, а третий с четвертым, затем победители пар сыграют в финале турнира. </p><p>Известно, что в матче между двумя игроками выиграет тот, чье мастерство больше. Мастерство $$$i$$$-го игрока равно $$$s_i$$$ и все уровни мастерства попарно различны (т.е. в массиве $$$s$$$ нет двух одинаковых значений).</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 10^4$$$) — количество наборов входных данных. </p><p>Единственная строка входных данных содержит четыре целых числа $$$s_1, s_2, s_3, s_4$$$ ($$$1 \le s_i \le 100$$$) — мастерство игроков. Гарантируется, что в массиве все числа различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите <span class="tex-font-style-tt">YES</span>, если турнир является <span class="tex-font-style-bf">честным</span>, или <span class="tex-font-style-tt">NO</span> в противном случае.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 7 9 5 4 5 6 9 5 3 8 1 6 5 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES NO YES NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим примеры:</p><ol> <li> в первом примере игроки $$$2$$$ и $$$3$$$ с навыками $$$7$$$ и $$$9$$$ выходят в финал; </li><li> во втором примере игроки $$$2$$$ и $$$4$$$ с навыками $$$5$$$ и $$$9$$$ выходят в финал. Игрок с навыком $$$6$$$ не прошел в финал, но игрок с навыком $$$5$$$ прошел в финал, поэтому турнир нечестен; </li><li> в третьем примере игроки $$$1$$$ и $$$3$$$ с навыками $$$5$$$ и $$$8$$$ выходят в финал; </li><li> в четвертом примере игроки $$$1$$$ и $$$3$$$ с навыками $$$6$$$ и $$$3$$$ выходят в финал. Игрок с навыком $$$5$$$ не прошел в финал, но игрок с навыком $$$3$$$ прошел в финал, поэтому турнир нечестен. </li></ol></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:28: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:'8124c5ae1a6c2de2',t:'MTY5NjY2NzMyMi43MDkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*800"]
1535B
1535
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$$$, состоящий из $$$n$$$ целых чисел.</p><p>Назовем пару индексов $$$i$$$, $$$j$$$ <span class="tex-font-style-bf">хорошей</span>, если $$$1 \le i &lt; j \le n$$$ и $$$\gcd(a_i, 2a_j) &gt; 1$$$ (где $$$\gcd(x, y)$$$ — наибольший общий делитель чисел $$$x$$$ и $$$y$$$).</p><p>Найдите максимальное количество <span class="tex-font-style-bf">хороших</span> пар индексов, если вы можете переупорядочить элементы массива $$$a$$$ произвольным образом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных. </p><p>Первая строка набора входных данных содержит одно целое число $$$n$$$ ($$$2 \le n \le 2000$$$) — количество элементов в массиве.</p><p>Вторая строка набора входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора выходных данных выведите одно целое число — максимальное количество <span class="tex-font-style-bf">хороших</span> пар индексов после переупорядочивания элементов массива $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 3 6 5 3 2 1 7 5 1 4 2 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 0 9 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере из условия элементы массива можно переставить следующим образом: $$$[6, 3, 5, 3]$$$.</p><p>В третьем примере из условия элементы массива можно переставить следующим образом: $$$[4, 4, 2, 1, 1]$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="9a508e7cdb14afce176c263c1f8c9825"/> <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="60b218a6c3a91fe751ac8150ebad932bcdaef025"/> <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='9a508e7cdb14afce176c263c1f8c9825'>&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%2F1535%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='9a508e7cdb14afce176c263c1f8c9825'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1535">Educational Codeforces Round 110 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left 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='9a508e7cdb14afce176c263c1f8c9825'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1535/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='9a508e7cdb14afce176c263c1f8c9825'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1005283"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='9a508e7cdb14afce176c263c1f8c9825'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1005283"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91386" title="Educational Codeforces Round 110 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13808:13809" 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/91481" title="91481" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13829:13830" 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/1535">Задачи</a></li> <li><a href="/contest/1535/submit">Отослать</a></li> <li><a href="/contest/1535/my">Мои посылки</a></li> <li><a href="/contest/1535/status">Статус</a></li> <li><a href="/contest/1535/hacks">Взломы</a></li> <li><a href="/contest/1535/standings">Положение</a></li> <li><a href="/contest/1535/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_bda59f54171e57b56bb7c0c5b593409ca765fc33"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$, состоящий из $$$n$$$ целых чисел.</p><p>Назовем пару индексов $$$i$$$, $$$j$$$ <span class="tex-font-style-bf">хорошей</span>, если $$$1 \le i &lt; j \le n$$$ и $$$\gcd(a_i, 2a_j) &gt; 1$$$ (где $$$\gcd(x, y)$$$ — наибольший общий делитель чисел $$$x$$$ и $$$y$$$).</p><p>Найдите максимальное количество <span class="tex-font-style-bf">хороших</span> пар индексов, если вы можете переупорядочить элементы массива $$$a$$$ произвольным образом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных. </p><p>Первая строка набора входных данных содержит одно целое число $$$n$$$ ($$$2 \le n \le 2000$$$) — количество элементов в массиве.</p><p>Вторая строка набора входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора выходных данных выведите одно целое число — максимальное количество <span class="tex-font-style-bf">хороших</span> пар индексов после переупорядочивания элементов массива $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 3 6 5 3 2 1 7 5 1 4 2 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 0 9 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере из условия элементы массива можно переставить следующим образом: $$$[6, 3, 5, 3]$$$.</p><p>В третьем примере из условия элементы массива можно переставить следующим образом: $$$[4, 4, 2, 1, 1]$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:28: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:'8124c5b6ac5c005f',t:'MTY5NjY2NzMyNC4wNTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*900"]
1535C
1535
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$$$, состоящая из символов <span class="tex-font-style-tt">0</span>, <span class="tex-font-style-tt">1</span> и <span class="tex-font-style-tt">?</span>.</p><p>Назовем строку <span class="tex-font-style-bf">нестабильной</span>, если она состоит из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span> и любые два соседних символа различаются (т. е. имеет вид <span class="tex-font-style-tt">010101...</span> или <span class="tex-font-style-tt">101010...</span>).</p><p>Назовем строку <span class="tex-font-style-bf">красивой</span>, если она состоит из символов <span class="tex-font-style-tt">0</span>, <span class="tex-font-style-tt">1</span> и <span class="tex-font-style-tt">?</span>, и в ней можно заменить символы <span class="tex-font-style-tt">?</span> на <span class="tex-font-style-tt">0</span> или <span class="tex-font-style-tt">1</span> (для каждого символа выбор происходит независимо), чтобы строка стала <span class="tex-font-style-bf">нестабильной</span>.</p><p>Например, строки <span class="tex-font-style-tt">0??10</span>, <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">???</span> являются красивыми, а строки <span class="tex-font-style-tt">00</span> и <span class="tex-font-style-tt">?1??1</span> — нет.</p><p>Посчитайте количество красивых непрерывных подстрок строки $$$s$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных. </p><p>Первая и единственная строка каждого набора содержит строку $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$), состоящую из символов <span class="tex-font-style-tt">0</span>, <span class="tex-font-style-tt">1</span> и <span class="tex-font-style-tt">?</span>.</p><p>Гарантируется, что сумма длин строк по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора выходных данных выведите одно целое число — количество <span class="tex-font-style-bf">красивых</span> подстрок строки $$$s$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 0?10 ??? ?10??1100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 6 25 </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="a2f269eef141265ecad333e3889f91cc"/> <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="60b218a6c3a91fe751ac8150ebad932bcdaef025"/> <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='a2f269eef141265ecad333e3889f91cc'>&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%2F1535%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='a2f269eef141265ecad333e3889f91cc'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1535">Educational Codeforces Round 110 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left 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='a2f269eef141265ecad333e3889f91cc'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1535/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='a2f269eef141265ecad333e3889f91cc'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1005284"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a2f269eef141265ecad333e3889f91cc'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1005284"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91386" title="Educational Codeforces Round 110 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13808:13809" 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/91481" title="91481" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13829:13830" 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/1535">Задачи</a></li> <li><a href="/contest/1535/submit">Отослать</a></li> <li><a href="/contest/1535/my">Мои посылки</a></li> <li><a href="/contest/1535/status">Статус</a></li> <li><a href="/contest/1535/hacks">Взломы</a></li> <li><a href="/contest/1535/standings">Положение</a></li> <li><a href="/contest/1535/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f8d1ba1f322dceeeaa3e6fa134aa0a80ecce1c1f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$, состоящая из символов <span class="tex-font-style-tt">0</span>, <span class="tex-font-style-tt">1</span> и <span class="tex-font-style-tt">?</span>.</p><p>Назовем строку <span class="tex-font-style-bf">нестабильной</span>, если она состоит из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span> и любые два соседних символа различаются (т. е. имеет вид <span class="tex-font-style-tt">010101...</span> или <span class="tex-font-style-tt">101010...</span>).</p><p>Назовем строку <span class="tex-font-style-bf">красивой</span>, если она состоит из символов <span class="tex-font-style-tt">0</span>, <span class="tex-font-style-tt">1</span> и <span class="tex-font-style-tt">?</span>, и в ней можно заменить символы <span class="tex-font-style-tt">?</span> на <span class="tex-font-style-tt">0</span> или <span class="tex-font-style-tt">1</span> (для каждого символа выбор происходит независимо), чтобы строка стала <span class="tex-font-style-bf">нестабильной</span>.</p><p>Например, строки <span class="tex-font-style-tt">0??10</span>, <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">???</span> являются красивыми, а строки <span class="tex-font-style-tt">00</span> и <span class="tex-font-style-tt">?1??1</span> — нет.</p><p>Посчитайте количество красивых непрерывных подстрок строки $$$s$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных. </p><p>Первая и единственная строка каждого набора содержит строку $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$), состоящую из символов <span class="tex-font-style-tt">0</span>, <span class="tex-font-style-tt">1</span> и <span class="tex-font-style-tt">?</span>.</p><p>Гарантируется, что сумма длин строк по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора выходных данных выведите одно целое число — количество <span class="tex-font-style-bf">красивых</span> подстрок строки $$$s$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 0?10 ??? ?10??1100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 6 25 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:28: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:'8124c5befcaf7a7d',t:'MTY5NjY2NzMyNS40MTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\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"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1400"]
1535D
1535
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>$$$2^k$$$ команд участвуют в плей-офф турнире. Турнир состоит из $$$2^k - 1$$$ игры. Они проводятся следующим образом: во-первых, команды делятся на пары: команда $$$1$$$ играет против команды $$$2$$$, команда $$$3$$$ играет против команды $$$4$$$ (именно в таком порядке) и так далее (таким образом, в этой фазе будет сыграно $$$2^{k-1}$$$ игры). Когда команда проигрывает игру, она выбывает, и каждая игра приводит к выбыванию одной команды (нет ничьих). После этого остается $$$2^{k-1}$$$ команд. Если остается только одна команда, она объявляется чемпионом; в противном случае играется еще $$$2^{k-2}$$$ игр: в первой из них победитель игры «$$$1$$$ против $$$2$$$» играет против победителя игры «$$$3$$$ против $$$4$$$», затем победитель игры «$$$5$$$ против $$$6$$$» играет против победителя игры «$$$7$$$ против $$$8$$$» и так далее. Этот процесс повторяется до тех пор, пока не останется только одна команда.</p><p>Например, на этом рисунке описан хронологический порядок игр с $$$k = 3$$$:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e120c1759082565bac13b78f57029903d66c0519.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Пусть строка $$$s$$$, состоящая из $$$2^k - 1$$$ символов, описывает результаты игр в хронологическом порядке следующим образом:</p><ul> <li> если $$$s_i$$$ равно <span class="tex-font-style-tt">0</span>, то команда с меньшим индексом выигрывает $$$i$$$-ю игру; </li><li> если $$$s_i$$$ равно <span class="tex-font-style-tt">1</span>, то команда с большим индексом выигрывает $$$i$$$-ю игру; </li><li> если $$$s_i$$$ равно <span class="tex-font-style-tt">?</span>, то результат $$$i$$$-й игры неизвестен (любая команда может выиграть эту игру). </li></ul><p>Пусть $$$f(s)$$$ — число <span class="tex-font-style-it">возможных победителей</span> турнира, описываемого строкой $$$s$$$. Команда $$$i$$$ является <span class="tex-font-style-it">возможным победителем</span> турнира, если можно заменить каждый <span class="tex-font-style-tt">?</span> на <span class="tex-font-style-tt">1</span> или <span class="tex-font-style-tt">0</span> таким образом, что команда $$$i$$$ является чемпионом.</p><p>Вам дается начальное состояние строки $$$s$$$. Вы должны обработать $$$q$$$ запросов следующей формы: </p><ul> <li> $$$p$$$ $$$c$$$ — заменить $$$s_p$$$ символом $$$c$$$ и вывести $$$f(s)$$$ в результате запроса. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$k$$$ ($$$1 \le k \le 18$$$).</p><p>Вторая строка содержит строку, состоящую из $$$2^k - 1$$$ символов — начальное состояние строки $$$s$$$. Каждый символ либо <span class="tex-font-style-tt">?</span>, <span class="tex-font-style-tt">0</span>, либо <span class="tex-font-style-tt">1</span>.</p><p>Третья строка содержит одно целое число $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — количество запросов.</p><p>Затем следует $$$q$$$ строк, строка $$$i$$$ содержит целое число $$$p$$$ и символ $$$c$$$ ($$$1 \le p \le 2^k - 1$$$; $$$c$$$ - это либо <span class="tex-font-style-tt">?</span>, <span class="tex-font-style-tt">0</span>, либо <span class="tex-font-style-tt">1</span>), описывающие запрос $$$i$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого запроса выведите одно целое число — $$$f(s)$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 0110?11 6 5 1 6 ? 7 ? 1 ? 5 ? 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 3 3 5 4 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="f544254ca1949417259b4436e581dfb8"/> <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="60b218a6c3a91fe751ac8150ebad932bcdaef025"/> <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='f544254ca1949417259b4436e581dfb8'>&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%2F1535%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='f544254ca1949417259b4436e581dfb8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1535">Educational Codeforces Round 110 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left 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='f544254ca1949417259b4436e581dfb8'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1535/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='f544254ca1949417259b4436e581dfb8'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1005285"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f544254ca1949417259b4436e581dfb8'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1005285"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91386" title="Educational Codeforces Round 110 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13808:13809" 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/91481" title="91481" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13829:13830" 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/1535">Задачи</a></li> <li><a href="/contest/1535/submit">Отослать</a></li> <li><a href="/contest/1535/my">Мои посылки</a></li> <li><a href="/contest/1535/status">Статус</a></li> <li><a href="/contest/1535/hacks">Взломы</a></li> <li><a href="/contest/1535/standings">Положение</a></li> <li><a href="/contest/1535/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_e061ea224fa24fd8d4873c477926d35f3c1b8810"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>$$$2^k$$$ команд участвуют в плей-офф турнире. Турнир состоит из $$$2^k - 1$$$ игры. Они проводятся следующим образом: во-первых, команды делятся на пары: команда $$$1$$$ играет против команды $$$2$$$, команда $$$3$$$ играет против команды $$$4$$$ (именно в таком порядке) и так далее (таким образом, в этой фазе будет сыграно $$$2^{k-1}$$$ игры). Когда команда проигрывает игру, она выбывает, и каждая игра приводит к выбыванию одной команды (нет ничьих). После этого остается $$$2^{k-1}$$$ команд. Если остается только одна команда, она объявляется чемпионом; в противном случае играется еще $$$2^{k-2}$$$ игр: в первой из них победитель игры «$$$1$$$ против $$$2$$$» играет против победителя игры «$$$3$$$ против $$$4$$$», затем победитель игры «$$$5$$$ против $$$6$$$» играет против победителя игры «$$$7$$$ против $$$8$$$» и так далее. Этот процесс повторяется до тех пор, пока не останется только одна команда.</p><p>Например, на этом рисунке описан хронологический порядок игр с $$$k = 3$$$:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e120c1759082565bac13b78f57029903d66c0519.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Пусть строка $$$s$$$, состоящая из $$$2^k - 1$$$ символов, описывает результаты игр в хронологическом порядке следующим образом:</p><ul> <li> если $$$s_i$$$ равно <span class="tex-font-style-tt">0</span>, то команда с меньшим индексом выигрывает $$$i$$$-ю игру; </li><li> если $$$s_i$$$ равно <span class="tex-font-style-tt">1</span>, то команда с большим индексом выигрывает $$$i$$$-ю игру; </li><li> если $$$s_i$$$ равно <span class="tex-font-style-tt">?</span>, то результат $$$i$$$-й игры неизвестен (любая команда может выиграть эту игру). </li></ul><p>Пусть $$$f(s)$$$ — число <span class="tex-font-style-it">возможных победителей</span> турнира, описываемого строкой $$$s$$$. Команда $$$i$$$ является <span class="tex-font-style-it">возможным победителем</span> турнира, если можно заменить каждый <span class="tex-font-style-tt">?</span> на <span class="tex-font-style-tt">1</span> или <span class="tex-font-style-tt">0</span> таким образом, что команда $$$i$$$ является чемпионом.</p><p>Вам дается начальное состояние строки $$$s$$$. Вы должны обработать $$$q$$$ запросов следующей формы: </p><ul> <li> $$$p$$$ $$$c$$$ — заменить $$$s_p$$$ символом $$$c$$$ и вывести $$$f(s)$$$ в результате запроса. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$k$$$ ($$$1 \le k \le 18$$$).</p><p>Вторая строка содержит строку, состоящую из $$$2^k - 1$$$ символов — начальное состояние строки $$$s$$$. Каждый символ либо <span class="tex-font-style-tt">?</span>, <span class="tex-font-style-tt">0</span>, либо <span class="tex-font-style-tt">1</span>.</p><p>Третья строка содержит одно целое число $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — количество запросов.</p><p>Затем следует $$$q$$$ строк, строка $$$i$$$ содержит целое число $$$p$$$ и символ $$$c$$$ ($$$1 \le p \le 2^k - 1$$$; $$$c$$$ - это либо <span class="tex-font-style-tt">?</span>, <span class="tex-font-style-tt">0</span>, либо <span class="tex-font-style-tt">1</span>), описывающие запрос $$$i$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого запроса выведите одно целое число — $$$f(s)$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 0110?11 6 5 1 6 ? 7 ? 1 ? 5 ? 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 3 3 5 4 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:28: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:'8124c5c78b1e78ff',t:'MTY5NjY2NzMyNi43NzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\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", "\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", "\u0434\u043f", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1800"]
1535E
1535
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.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>Вам задано корневое дерево. Каждая вершина дерева содержит $$$a_i$$$ тонн золота, стоящее $$$c_i$$$ за тонну. Первоначально, дерево состоит только из корня с номером $$$0$$$, в котором $$$a_0$$$ тонн золота с ценой $$$c_0$$$ за тонну.</p><p>Всего есть $$$q$$$ запросов. Каждый запрос одного из двух видов: </p><ol> <li> Подвесить вершину $$$i$$$ (где $$$i$$$ — это номер запроса) за некоторую вершину $$$p_i$$$; вершина $$$i$$$ будет содержать $$$a_i$$$ тонн золота с ценой $$$c_i$$$ за тонну. Гарантируется, что $$$c_i &gt; c_{p_i}$$$. </li><li> Для заданной вершины $$$v_i$$$ рассмотрим простой путь от $$$v_i$$$ к корню. Нам нужно приобрести $$$w_i$$$ тонн золота из вершин на этом пути, потратив наименьшее количество денег. Если на этом пути недостаточно золота, <span class="tex-font-style-bf">мы покупаем все что можно</span>. </li></ol><p>Если мы покупаем $$$x$$$ тон золота в некоторой вершине $$$v$$$, то оставшееся количество золота в ней уменьшается на $$$x$$$ (очевидно, мы не можем купить больше золота, чем есть в вершине на данный момент). Для каждого запроса второго вида посчитайте, сколько тонн золота мы купим в результате и сколько мы на это потратим.</p><p>Заметим, что вы должны решить данную задачу в <span class="tex-font-style-tt">онлайне</span>. То есть вы не можете считать все входные данные заранее. Вы можете считать очередной запрос только после того как выведете ответ на предыдущий, поэтому не забывайте сбрасывать поток вывода после вывода ответа. Вы можете использовать такие функции как <span class="tex-font-style-tt">fflush(stdout)</span> в <span class="tex-font-style-tt">C++</span>, <span class="tex-font-style-tt">BufferedWriter.flush</span> в <span class="tex-font-style-tt">Java</span> или похожие после каждого вывода в программе. По стандарту (если вы не модифицировали I/O), <span class="tex-font-style-tt">endl</span> сбрасывает <span class="tex-font-style-tt">cout</span> в <span class="tex-font-style-tt">C++</span>, а <span class="tex-font-style-tt">System.out.println</span> в <span class="tex-font-style-tt">Java</span> (или <span class="tex-font-style-tt">println</span> в <span class="tex-font-style-tt">Kotlin</span>) сбрасывают поток вывода автоматически. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы три целых числа $$$q$$$, $$$a_0$$$ и $$$c_0$$$ ($$$1 \le q \le 3 \cdot 10^5$$$; $$$1 \le a_0, c_0 &lt; 10^6$$$) — количество запросов, количество золота в корне и его цена за тонну.</p><p>В следующих $$$q$$$ строках заданы описания запросов: $$$i$$$-й запрос имеет один из следующих видов: </p><ul> <li> «$$$1$$$ $$$p_i$$$ $$$a_i$$$ $$$c_i$$$» ($$$0 \le p_i &lt; i$$$; $$$1 \le a_i, c_i &lt; 10^6$$$): подвесить вершину $$$i$$$ за вершину $$$p_i$$$. Вершина $$$i$$$ будет содержать $$$a_i$$$ тонн золота по цене $$$c_i$$$ за тонну. Гарантируется, что вершина $$$p_i$$$ существует и $$$c_i &gt; c_{p_i}$$$.</li><li> «$$$2$$$ $$$v_i$$$ $$$w_i$$$» ($$$0 \le v_i &lt; i$$$; $$$1 \le w_i &lt; 10^6$$$): приобрести $$$w_i$$$ тонн золота из вершин на пути из $$$v_i$$$ в $$$0$$$, потратив минимальное количество денег. Если на пути золота недостаточно, мы покупаем все что есть. Гарантируется, что вершина $$$v_i$$$ существует. </li></ul><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> 5 5 2 2 0 2 1 0 3 4 2 2 4 1 0 1 3 2 4 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 4 4 10 1 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим пример:</p><p>В первом запросе, дерево состоит только из корня, поэтому мы приобретаем $$$2$$$ тонны золота и платим $$$2 \cdot 2 = 4$$$. В корне осталось $$$3$$$ тонны.</p><p>Во втором запросе, вы подвешиваем вершину $$$2$$$ за вершину $$$0$$$. В вершине $$$2$$$ сейчас $$$3$$$ тонны золота по цене $$$4$$$ за тонну.</p><p>В третьем запросе, простой путь из $$$2$$$ в $$$0$$$ содержит только вершины $$$0$$$ и $$$2$$$, а так как $$$c_0 &lt; c_2$$$, мы покупаем оставшиеся $$$3$$$ тонны золота в вершине $$$0$$$ и $$$1$$$ тонну в вершине $$$2$$$. Таким образом, мы приобрели $$$3 + 1 = 4$$$ тонны и заплатили $$$3 \cdot 2 + 1 \cdot 4 = 10$$$. Теперь, вершина $$$0$$$ осталась без золота, а вершине $$$2$$$ осталось $$$2$$$ тонны золота.</p><p>В четвертом запросе, мы подвешиваем вершину $$$4$$$ за вершину $$$0$$$. В вершине $$$4$$$ сейчас $$$1$$$ тонна золота по цене $$$3$$$.</p><p>В пятом запросе, простой путь из $$$4$$$ в $$$0$$$ состоит только из вершин $$$0$$$ и $$$4$$$. Но так как в вершине $$$0$$$ уже нет золота, а в вершине $$$4$$$ только $$$1$$$ тонна, то мы покупаем $$$1$$$ тонну из вершины $$$4$$$ и тратим $$$1 \cdot 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="b7c5c23274dbcec8dba4800f920ae461"/> <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="60b218a6c3a91fe751ac8150ebad932bcdaef025"/> <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='b7c5c23274dbcec8dba4800f920ae461'>&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%2F1535%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='b7c5c23274dbcec8dba4800f920ae461'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1535">Educational Codeforces Round 110 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left 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='b7c5c23274dbcec8dba4800f920ae461'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1535/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='b7c5c23274dbcec8dba4800f920ae461'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1005286"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b7c5c23274dbcec8dba4800f920ae461'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1005286"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91386" title="Educational Codeforces Round 110 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13808:13809" 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/91481" title="91481" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13829:13830" 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/1535">Задачи</a></li> <li><a href="/contest/1535/submit">Отослать</a></li> <li><a href="/contest/1535/my">Мои посылки</a></li> <li><a href="/contest/1535/status">Статус</a></li> <li><a href="/contest/1535/hacks">Взломы</a></li> <li><a href="/contest/1535/standings">Положение</a></li> <li><a href="/contest/1535/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_021b5aac74e50a26bec9bcdc9edca026a14a0b6d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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.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>Вам задано корневое дерево. Каждая вершина дерева содержит $$$a_i$$$ тонн золота, стоящее $$$c_i$$$ за тонну. Первоначально, дерево состоит только из корня с номером $$$0$$$, в котором $$$a_0$$$ тонн золота с ценой $$$c_0$$$ за тонну.</p><p>Всего есть $$$q$$$ запросов. Каждый запрос одного из двух видов: </p><ol> <li> Подвесить вершину $$$i$$$ (где $$$i$$$ — это номер запроса) за некоторую вершину $$$p_i$$$; вершина $$$i$$$ будет содержать $$$a_i$$$ тонн золота с ценой $$$c_i$$$ за тонну. Гарантируется, что $$$c_i &gt; c_{p_i}$$$. </li><li> Для заданной вершины $$$v_i$$$ рассмотрим простой путь от $$$v_i$$$ к корню. Нам нужно приобрести $$$w_i$$$ тонн золота из вершин на этом пути, потратив наименьшее количество денег. Если на этом пути недостаточно золота, <span class="tex-font-style-bf">мы покупаем все что можно</span>. </li></ol><p>Если мы покупаем $$$x$$$ тон золота в некоторой вершине $$$v$$$, то оставшееся количество золота в ней уменьшается на $$$x$$$ (очевидно, мы не можем купить больше золота, чем есть в вершине на данный момент). Для каждого запроса второго вида посчитайте, сколько тонн золота мы купим в результате и сколько мы на это потратим.</p><p>Заметим, что вы должны решить данную задачу в <span class="tex-font-style-tt">онлайне</span>. То есть вы не можете считать все входные данные заранее. Вы можете считать очередной запрос только после того как выведете ответ на предыдущий, поэтому не забывайте сбрасывать поток вывода после вывода ответа. Вы можете использовать такие функции как <span class="tex-font-style-tt">fflush(stdout)</span> в <span class="tex-font-style-tt">C++</span>, <span class="tex-font-style-tt">BufferedWriter.flush</span> в <span class="tex-font-style-tt">Java</span> или похожие после каждого вывода в программе. По стандарту (если вы не модифицировали I/O), <span class="tex-font-style-tt">endl</span> сбрасывает <span class="tex-font-style-tt">cout</span> в <span class="tex-font-style-tt">C++</span>, а <span class="tex-font-style-tt">System.out.println</span> в <span class="tex-font-style-tt">Java</span> (или <span class="tex-font-style-tt">println</span> в <span class="tex-font-style-tt">Kotlin</span>) сбрасывают поток вывода автоматически. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы три целых числа $$$q$$$, $$$a_0$$$ и $$$c_0$$$ ($$$1 \le q \le 3 \cdot 10^5$$$; $$$1 \le a_0, c_0 &lt; 10^6$$$) — количество запросов, количество золота в корне и его цена за тонну.</p><p>В следующих $$$q$$$ строках заданы описания запросов: $$$i$$$-й запрос имеет один из следующих видов: </p><ul> <li> «$$$1$$$ $$$p_i$$$ $$$a_i$$$ $$$c_i$$$» ($$$0 \le p_i &lt; i$$$; $$$1 \le a_i, c_i &lt; 10^6$$$): подвесить вершину $$$i$$$ за вершину $$$p_i$$$. Вершина $$$i$$$ будет содержать $$$a_i$$$ тонн золота по цене $$$c_i$$$ за тонну. Гарантируется, что вершина $$$p_i$$$ существует и $$$c_i &gt; c_{p_i}$$$.</li><li> «$$$2$$$ $$$v_i$$$ $$$w_i$$$» ($$$0 \le v_i &lt; i$$$; $$$1 \le w_i &lt; 10^6$$$): приобрести $$$w_i$$$ тонн золота из вершин на пути из $$$v_i$$$ в $$$0$$$, потратив минимальное количество денег. Если на пути золота недостаточно, мы покупаем все что есть. Гарантируется, что вершина $$$v_i$$$ существует. </li></ul><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> 5 5 2 2 0 2 1 0 3 4 2 2 4 1 0 1 3 2 4 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 4 4 10 1 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим пример:</p><p>В первом запросе, дерево состоит только из корня, поэтому мы приобретаем $$$2$$$ тонны золота и платим $$$2 \cdot 2 = 4$$$. В корне осталось $$$3$$$ тонны.</p><p>Во втором запросе, вы подвешиваем вершину $$$2$$$ за вершину $$$0$$$. В вершине $$$2$$$ сейчас $$$3$$$ тонны золота по цене $$$4$$$ за тонну.</p><p>В третьем запросе, простой путь из $$$2$$$ в $$$0$$$ содержит только вершины $$$0$$$ и $$$2$$$, а так как $$$c_0 &lt; c_2$$$, мы покупаем оставшиеся $$$3$$$ тонны золота в вершине $$$0$$$ и $$$1$$$ тонну в вершине $$$2$$$. Таким образом, мы приобрели $$$3 + 1 = 4$$$ тонны и заплатили $$$3 \cdot 2 + 1 \cdot 4 = 10$$$. Теперь, вершина $$$0$$$ осталась без золота, а вершине $$$2$$$ осталось $$$2$$$ тонны золота.</p><p>В четвертом запросе, мы подвешиваем вершину $$$4$$$ за вершину $$$0$$$. В вершине $$$4$$$ сейчас $$$1$$$ тонна золота по цене $$$3$$$.</p><p>В пятом запросе, простой путь из $$$4$$$ в $$$0$$$ состоит только из вершин $$$0$$$ и $$$4$$$. Но так как в вершине $$$0$$$ уже нет золота, а в вершине $$$4$$$ только $$$1$$$ тонна, то мы покупаем $$$1$$$ тонну из вершины $$$4$$$ и тратим $$$1 \cdot 3 = 3$$$. Теперь в вершине $$$4$$$ больше не осталось золота.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:28: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:'8124c5d01a691625',t:'MTY5NjY2NzMyOC4xMzIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2200"]
1535F
1535
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>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Предположим, вам даны две строки $$$a$$$ и $$$b$$$. Вы можете применить следующую операцию любое количество раз: выбрать любую <span class="tex-font-style-bf">непрерывную</span> подстроку $$$a$$$ или $$$b$$$ и отсортировать символы в ней в порядке неубывания. Пусть $$$f(a, b)$$$ — минимальное количество операций, которое необходимо применить, чтобы сделать строки равными (или $$$f(a, b) = 1337$$$, если невозможно сделать $$$a$$$ и $$$b$$$ равными с помощью этих операций).</p><p>Например: </p><ul> <li> $$$f(\text{ab}, \text{ab}) = 0$$$; </li><li> $$$f(\text{ba}, \text{ab}) = 1$$$ (за одну операцию мы можем отсортировать всю первую строку); </li><li> $$$f(\text{ebcda}, \text{ecdba}) = 1$$$ (за одну операцию мы можем отсортировать подстроку со $$$2$$$-го по $$$4$$$-й символ второй строки); </li><li> $$$f(\text{a}, \text{b}) = 1337$$$. </li></ul><p>Вам задано $$$n$$$ строк $$$s_1, s_2, \dots, s_k$$$ одинаковой длины. Вычислите $$$\sum \limits_{i = 1}^{n} \sum\limits_{j = i + 1}^{n} f(s_i, s_j)$$$.</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_i$$$, состоящую из строчных латинских букв. $$$|s_1| = |s_2| = \ldots = |s_n|$$$ и $$$n \cdot |s_1| \le 2 \cdot 10^5$$$. Все заданные строки попарно различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число: $$$\sum \limits_{i = 1}^{n} \sum\limits_{j = i + 1}^{n} f(s_i, s_j)$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 zzz bac abc acb </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4015 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 a b </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1337 </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="77920d0e067f696d7c909082409aa2d4"/> <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="60b218a6c3a91fe751ac8150ebad932bcdaef025"/> <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='77920d0e067f696d7c909082409aa2d4'>&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%2F1535%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='77920d0e067f696d7c909082409aa2d4'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1535">Educational Codeforces Round 110 (рейтинговый для Див. 2)</a></th> </tr> <tr> <td class="left 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='77920d0e067f696d7c909082409aa2d4'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1535/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др."> строки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Хэши, хэш-таблицы"> хэши </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *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='77920d0e067f696d7c909082409aa2d4'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1005287"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='77920d0e067f696d7c909082409aa2d4'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1005287"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91386" title="Educational Codeforces Round 110 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13808:13809" 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/91481" title="91481" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13829:13830" 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/1535">Задачи</a></li> <li><a href="/contest/1535/submit">Отослать</a></li> <li><a href="/contest/1535/my">Мои посылки</a></li> <li><a href="/contest/1535/status">Статус</a></li> <li><a href="/contest/1535/hacks">Взломы</a></li> <li><a href="/contest/1535/standings">Положение</a></li> <li><a href="/contest/1535/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c96cc2874112a8959da7aa9a128ba3810b42da59"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Предположим, вам даны две строки $$$a$$$ и $$$b$$$. Вы можете применить следующую операцию любое количество раз: выбрать любую <span class="tex-font-style-bf">непрерывную</span> подстроку $$$a$$$ или $$$b$$$ и отсортировать символы в ней в порядке неубывания. Пусть $$$f(a, b)$$$ — минимальное количество операций, которое необходимо применить, чтобы сделать строки равными (или $$$f(a, b) = 1337$$$, если невозможно сделать $$$a$$$ и $$$b$$$ равными с помощью этих операций).</p><p>Например: </p><ul> <li> $$$f(\text{ab}, \text{ab}) = 0$$$; </li><li> $$$f(\text{ba}, \text{ab}) = 1$$$ (за одну операцию мы можем отсортировать всю первую строку); </li><li> $$$f(\text{ebcda}, \text{ecdba}) = 1$$$ (за одну операцию мы можем отсортировать подстроку со $$$2$$$-го по $$$4$$$-й символ второй строки); </li><li> $$$f(\text{a}, \text{b}) = 1337$$$. </li></ul><p>Вам задано $$$n$$$ строк $$$s_1, s_2, \dots, s_k$$$ одинаковой длины. Вычислите $$$\sum \limits_{i = 1}^{n} \sum\limits_{j = i + 1}^{n} f(s_i, s_j)$$$.</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_i$$$, состоящую из строчных латинских букв. $$$|s_1| = |s_2| = \ldots = |s_n|$$$ и $$$n \cdot |s_1| \le 2 \cdot 10^5$$$. Все заданные строки попарно различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число: $$$\sum \limits_{i = 1}^{n} \sum\limits_{j = i + 1}^{n} f(s_i, s_j)$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 zzz bac abc acb </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4015 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 a b </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1337 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:28: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:'8124c5d88d8e16c7',t:'MTY5NjY2NzMyOS41MTEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\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.", "\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"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u043e\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "\u0445\u044d\u0448\u0438", "*3000"]
1536A
1536
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 слишком запутанная. Просто сделайте формальное условие». В связи с этим Омкар дает вам массив $$$a = [a_1, a_2, \ldots, a_n]$$$ из $$$n$$$ попарно различных целых чисел. Массив $$$b = [b_1, b_2, \ldots, b_k]$$$ называется <span class="tex-font-style-bf">хорошим</span>, если для любых различных элементов $$$b_i, b_j$$$ массива $$$b$$$, $$$|b_i-b_j|$$$ встречается в $$$b$$$ хотя бы один раз. Кроме того, все элементы $$$b$$$ должны быть попарно различными. Можете ли вы добавить несколько (возможно, $$$0$$$) целых чисел в $$$a$$$, чтобы получился <span class="tex-font-style-bf">хороший</span> массив $$$b$$$ <span class="tex-font-style-bf">размером не более $$$300$$$</span>? Если $$$a$$$ уже <span class="tex-font-style-bf">хороший</span>, вы не обязаны добавлять никаких элементов.</p><p>Например, массив $$$[3, 6, 9]$$$ является <span class="tex-font-style-bf">хорошим</span>, поскольку $$$|6-3|=|9-6| = 3$$$, встречается в массиве, и $$$|9-3| = 6$$$, встречается в массиве, тогда как массив $$$[4, 2, 0, 6, 9]$$$ не является <span class="tex-font-style-bf">хорошим</span>, поскольку $$$|9-4| = 5$$$ не встречается в массиве. </p><p>Для целых чисел $$$x$$$ и $$$y$$$, $$$|x-y| = x-y$$$, если $$$x &gt; y$$$ и $$$|x-y| = y-x$$$ в противном случае.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит $$$t$$$ ($$$1 \leq t \leq 50$$$), количество наборов входных данных. Далее следует описание наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$2 \leq n \leq 100$$$) — длину массива $$$a$$$.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ <span class="tex-font-style-bf">попарно различных</span> целых чисел $$$a_1, a_2, \cdots, a_n$$$ ($$$-100 \leq a_i \leq 100$$$) — элементы массива $$$a$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую <span class="tex-font-style-tt">YES</span>, если Омкар может создать <span class="tex-font-style-bf">хороший</span> массив $$$b$$$ путем добавления целых чисел к $$$a$$$ и <span class="tex-font-style-tt">NO</span> в противном случае. Регистр каждой буквы не имеет значения, поэтому <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>, выведите вторую строку, содержащую одно целое число $$$k$$$ ($$$n \leq k \leq 300$$$). </p><p>Затем выведите одну строку, содержащую $$$k$$$ <span class="tex-font-style-bf">попарно различных</span> целых чисел $$$b_1, b_2, \cdots, b_k$$$ ($$$-10^9 \leq b_i \leq 10^9$$$) — элементы <span class="tex-font-style-bf">хорошего</span> массива $$$b$$$. $$$b_1, b_2, \cdots, b_k$$$ могут быть в любом порядке. Для каждого $$$a_i$$$ из $$$a$$$, $$$a_i$$$ должно хотя бы раз встречаться в $$$b$$$.</p><p>Можно показать, что если Омкар может создать такой массив $$$b$$$, то он может сделать это и таким образом, чтобы удовлетворить вышеуказанным ограничениям.</p><p>Если существует несколько решений, можно вывести любое. </p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 3 0 9 2 3 4 5 -7 3 13 -2 8 4 4 8 12 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> yes 4 6 0 3 9 yEs 5 5 3 1 2 4 NO Yes 6 8 12 6 2 4 10 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого набора входных данных можно добавить целые числа к $$$a$$$, чтобы получить массив $$$b = [3, 0, 6, 9, 3]$$$. Обратите внимание, что $$$|6-3| = |9-6| = |3-0| = 3$$$ и $$$3$$$ встречается в $$$b$$$, $$$|6-0| = |9-3| = 6$$$ и $$$6$$$ встречается в $$$b$$$, а также $$$|9-0| = 9$$$ встречается в $$$b$$$, поэтому $$$b$$$ <span class="tex-font-style-bf">хороший</span>.</p><p>Для второго набора входных данных можно добавить целые числа к $$$a$$$, чтобы получить массив $$$b = [5, 3, 1, 2, 4]$$$. Здесь $$$|2-1| = |3-2| = |4-3| = |5-4| = 1$$$ встречается в $$$b$$$, $$$|3-1| = |4-2| = |5-3| = 2$$$ встречается в $$$b$$$, $$$|4-1| = |5-2| = 3$$$ встречается в $$$b$$$, и $$$|5-1| = 4$$$ встречается в $$$b$$$, поэтому $$$b$$$ является <span class="tex-font-style-bf">хорошим</span>.</p><p>Для четвертого набора входных данных можно добавить целые числа к $$$a$$$, чтобы получить массив $$$b = [8, 12, 6, 2, 4, 10]$$$. Здесь $$$|4-2| = |6-4| = |8-6| = |10-8| = |12-10| = 2$$$ встречается в $$$b$$$, $$$|6-2| = |8-4| = |10-6| = |12-8| = 4$$$ встречается в $$$b$$$, $$$|8-2| = |10-4| = |12-6| = 6$$$ встречается в $$$b$$$, $$$|10-2| = |12-4| = 8$$$ встречается в $$$b$$$, а также $$$|12-2| = 10$$$ встречается в $$$b$$$, поэтому $$$b$$$ <span class="tex-font-style-bf">хороший</span>.</p><p>Можно доказать, что для всех остальных наборов входных данных невозможно получить <span class="tex-font-style-bf">хороший</span> массив $$$b$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="046cc5fb6ed4417d9346c0b7df9d3c75"/> <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="c5b14aed5c3545d647c4685d950ef358bc98f539"/> <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='046cc5fb6ed4417d9346c0b7df9d3c75'>&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%2F1536%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='046cc5fb6ed4417d9346c0b7df9d3c75'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1536">Codeforces Round 724 (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='046cc5fb6ed4417d9346c0b7df9d3c75'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1536/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *800 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='046cc5fb6ed4417d9346c0b7df9d3c75'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1007469"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='046cc5fb6ed4417d9346c0b7df9d3c75'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1007469"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91438" title="Codeforces Round #724 (Rated for Div 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13818" resourceName="Codeforces Round #724 (Rated for Div 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/91520" title="Codeforces Round #724 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13842" resourceName="Codeforces Round #724 — 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/1536">Задачи</a></li> <li><a href="/contest/1536/submit">Отослать</a></li> <li><a href="/contest/1536/my">Мои посылки</a></li> <li><a href="/contest/1536/status">Статус</a></li> <li><a href="/contest/1536/hacks">Взломы</a></li> <li><a href="/contest/1536/room/1">Комната</a></li> <li><a href="/contest/1536/standings">Положение</a></li> <li><a href="/contest/1536/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_173c1071f5d1b2cb974691a868bc52b91f456991"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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 слишком запутанная. Просто сделайте формальное условие». В связи с этим Омкар дает вам массив $$$a = [a_1, a_2, \ldots, a_n]$$$ из $$$n$$$ попарно различных целых чисел. Массив $$$b = [b_1, b_2, \ldots, b_k]$$$ называется <span class="tex-font-style-bf">хорошим</span>, если для любых различных элементов $$$b_i, b_j$$$ массива $$$b$$$, $$$|b_i-b_j|$$$ встречается в $$$b$$$ хотя бы один раз. Кроме того, все элементы $$$b$$$ должны быть попарно различными. Можете ли вы добавить несколько (возможно, $$$0$$$) целых чисел в $$$a$$$, чтобы получился <span class="tex-font-style-bf">хороший</span> массив $$$b$$$ <span class="tex-font-style-bf">размером не более $$$300$$$</span>? Если $$$a$$$ уже <span class="tex-font-style-bf">хороший</span>, вы не обязаны добавлять никаких элементов.</p><p>Например, массив $$$[3, 6, 9]$$$ является <span class="tex-font-style-bf">хорошим</span>, поскольку $$$|6-3|=|9-6| = 3$$$, встречается в массиве, и $$$|9-3| = 6$$$, встречается в массиве, тогда как массив $$$[4, 2, 0, 6, 9]$$$ не является <span class="tex-font-style-bf">хорошим</span>, поскольку $$$|9-4| = 5$$$ не встречается в массиве. </p><p>Для целых чисел $$$x$$$ и $$$y$$$, $$$|x-y| = x-y$$$, если $$$x &gt; y$$$ и $$$|x-y| = y-x$$$ в противном случае.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит $$$t$$$ ($$$1 \leq t \leq 50$$$), количество наборов входных данных. Далее следует описание наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$2 \leq n \leq 100$$$) — длину массива $$$a$$$.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ <span class="tex-font-style-bf">попарно различных</span> целых чисел $$$a_1, a_2, \cdots, a_n$$$ ($$$-100 \leq a_i \leq 100$$$) — элементы массива $$$a$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую <span class="tex-font-style-tt">YES</span>, если Омкар может создать <span class="tex-font-style-bf">хороший</span> массив $$$b$$$ путем добавления целых чисел к $$$a$$$ и <span class="tex-font-style-tt">NO</span> в противном случае. Регистр каждой буквы не имеет значения, поэтому <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>, выведите вторую строку, содержащую одно целое число $$$k$$$ ($$$n \leq k \leq 300$$$). </p><p>Затем выведите одну строку, содержащую $$$k$$$ <span class="tex-font-style-bf">попарно различных</span> целых чисел $$$b_1, b_2, \cdots, b_k$$$ ($$$-10^9 \leq b_i \leq 10^9$$$) — элементы <span class="tex-font-style-bf">хорошего</span> массива $$$b$$$. $$$b_1, b_2, \cdots, b_k$$$ могут быть в любом порядке. Для каждого $$$a_i$$$ из $$$a$$$, $$$a_i$$$ должно хотя бы раз встречаться в $$$b$$$.</p><p>Можно показать, что если Омкар может создать такой массив $$$b$$$, то он может сделать это и таким образом, чтобы удовлетворить вышеуказанным ограничениям.</p><p>Если существует несколько решений, можно вывести любое. </p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 3 0 9 2 3 4 5 -7 3 13 -2 8 4 4 8 12 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> yes 4 6 0 3 9 yEs 5 5 3 1 2 4 NO Yes 6 8 12 6 2 4 10 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого набора входных данных можно добавить целые числа к $$$a$$$, чтобы получить массив $$$b = [3, 0, 6, 9, 3]$$$. Обратите внимание, что $$$|6-3| = |9-6| = |3-0| = 3$$$ и $$$3$$$ встречается в $$$b$$$, $$$|6-0| = |9-3| = 6$$$ и $$$6$$$ встречается в $$$b$$$, а также $$$|9-0| = 9$$$ встречается в $$$b$$$, поэтому $$$b$$$ <span class="tex-font-style-bf">хороший</span>.</p><p>Для второго набора входных данных можно добавить целые числа к $$$a$$$, чтобы получить массив $$$b = [5, 3, 1, 2, 4]$$$. Здесь $$$|2-1| = |3-2| = |4-3| = |5-4| = 1$$$ встречается в $$$b$$$, $$$|3-1| = |4-2| = |5-3| = 2$$$ встречается в $$$b$$$, $$$|4-1| = |5-2| = 3$$$ встречается в $$$b$$$, и $$$|5-1| = 4$$$ встречается в $$$b$$$, поэтому $$$b$$$ является <span class="tex-font-style-bf">хорошим</span>.</p><p>Для четвертого набора входных данных можно добавить целые числа к $$$a$$$, чтобы получить массив $$$b = [8, 12, 6, 2, 4, 10]$$$. Здесь $$$|4-2| = |6-4| = |8-6| = |10-8| = |12-10| = 2$$$ встречается в $$$b$$$, $$$|6-2| = |8-4| = |10-6| = |12-8| = 4$$$ встречается в $$$b$$$, $$$|8-2| = |10-4| = |12-6| = 6$$$ встречается в $$$b$$$, $$$|10-2| = |12-4| = 8$$$ встречается в $$$b$$$, а также $$$|12-2| = 10$$$ встречается в $$$b$$$, поэтому $$$b$$$ <span class="tex-font-style-bf">хороший</span>.</p><p>Можно доказать, что для всех остальных наборов входных данных невозможно получить <span class="tex-font-style-bf">хороший</span> массив $$$b$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:28: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:'8124c5e10b4a75b3',t:'MTY5NjY2NzMzMC44ODIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*800"]
1536B
1536
B
ru
B. Принцесса Веруртейлунга
<div class="problem-statement"><div class="header"><div class="title">B. Принцесса Веруртейлунга</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Я, Фишль, принцесса Веруртейлунга, спустилась на эту землю по зову судьбы — О, ты тоже путешественница из другого мира?</span> <span class="tex-font-style-it">Очень хорошо, я разрешаю вам путешествовать со мной.</span></p><p>Нет ничего удивительного в том, что Фишль говорит, так странно выбирая выражения. Однако на этот раз даже Оз, ее друг-ворон, не может истолковать их! Может быть, вы поможете нам понять, что говорит эта юная принцесса?</p><p>Вам дана строка из $$$n$$$ строчных латинских букв — слово, которое только что произнесла Фишль. Вы думаете, что MEX строки может помочь вам найти смысл этого сообщения. MEX строки определяется как самая короткая строка, которая <span class="tex-font-style-bf">не</span> встречается как непрерывная подстрока во входных данных. Если существует несколько таких строк, то за MEX считается лексикографически наименьшая из них. Обратите внимание, что пустая подстрока НЕ считается MEX.</p><p>Строка $$$a$$$ лексикографически меньше строки $$$b$$$, если и только если выполняется один из следующих пунктов:</p><ul><li> $$$a$$$ — префикс $$$b$$$, но $$$a \ne b$$$;</li><li> в первой позиции, где $$$a$$$ и $$$b$$$ различны, в строке $$$a$$$ находится буква, которая встречается в алфавите раньше, чем соответствующая буква в $$$b$$$.</li></ul><p>Строка $$$a$$$ является подстрокой $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, ни одного или всех) символов из начала и нескольких (возможно, ни одного или всех) символов из конца.</p><p>Узнайте, что представляет собой строка MEX!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит количество наборов входных данных $$$t$$$ ($$$1 \leq t \leq 1000$$$). Далее следует описание наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит целое число $$$n$$$ ($$$1 \leq n \leq 1000$$$) — длина слова. Вторая строка каждого набора входных данных содержит одну строку из $$$n$$$ строчных латинских букв.</p><p>Сумма $$$n$$$ по всем наборам входных данных не превышает $$$1000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите MEX строки в отдельной строке.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 28 qaabzwsxedcrfvtgbyhnujmiklop 13 cleanairactbd 10 aannttoonn </pre></div><div class="output"><div class="title">Выходные данные</div><pre> ac f b </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="c1b4c19e930f0917af80189d214ce21b"/> <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="c5b14aed5c3545d647c4685d950ef358bc98f539"/> <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='c1b4c19e930f0917af80189d214ce21b'>&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%2F1536%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='c1b4c19e930f0917af80189d214ce21b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1536">Codeforces Round 724 (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='c1b4c19e930f0917af80189d214ce21b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1536/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др."> строки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *1200 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c1b4c19e930f0917af80189d214ce21b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1007470"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c1b4c19e930f0917af80189d214ce21b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1007470"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91438" title="Codeforces Round #724 (Rated for Div 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13818" resourceName="Codeforces Round #724 (Rated for Div 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/91520" title="Codeforces Round #724 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13842" resourceName="Codeforces Round #724 — 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/1536">Задачи</a></li> <li><a href="/contest/1536/submit">Отослать</a></li> <li><a href="/contest/1536/my">Мои посылки</a></li> <li><a href="/contest/1536/status">Статус</a></li> <li><a href="/contest/1536/hacks">Взломы</a></li> <li><a href="/contest/1536/room/1">Комната</a></li> <li><a href="/contest/1536/standings">Положение</a></li> <li><a href="/contest/1536/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f87094ea05c5280020e5cdfaa64ed936ff85e675"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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><span class="tex-font-style-it">Я, Фишль, принцесса Веруртейлунга, спустилась на эту землю по зову судьбы — О, ты тоже путешественница из другого мира?</span> <span class="tex-font-style-it">Очень хорошо, я разрешаю вам путешествовать со мной.</span></p><p>Нет ничего удивительного в том, что Фишль говорит, так странно выбирая выражения. Однако на этот раз даже Оз, ее друг-ворон, не может истолковать их! Может быть, вы поможете нам понять, что говорит эта юная принцесса?</p><p>Вам дана строка из $$$n$$$ строчных латинских букв — слово, которое только что произнесла Фишль. Вы думаете, что MEX строки может помочь вам найти смысл этого сообщения. MEX строки определяется как самая короткая строка, которая <span class="tex-font-style-bf">не</span> встречается как непрерывная подстрока во входных данных. Если существует несколько таких строк, то за MEX считается лексикографически наименьшая из них. Обратите внимание, что пустая подстрока НЕ считается MEX.</p><p>Строка $$$a$$$ лексикографически меньше строки $$$b$$$, если и только если выполняется один из следующих пунктов:</p><ul><li> $$$a$$$ — префикс $$$b$$$, но $$$a \ne b$$$;</li><li> в первой позиции, где $$$a$$$ и $$$b$$$ различны, в строке $$$a$$$ находится буква, которая встречается в алфавите раньше, чем соответствующая буква в $$$b$$$.</li></ul><p>Строка $$$a$$$ является подстрокой $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, ни одного или всех) символов из начала и нескольких (возможно, ни одного или всех) символов из конца.</p><p>Узнайте, что представляет собой строка MEX!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит количество наборов входных данных $$$t$$$ ($$$1 \leq t \leq 1000$$$). Далее следует описание наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит целое число $$$n$$$ ($$$1 \leq n \leq 1000$$$) — длина слова. Вторая строка каждого набора входных данных содержит одну строку из $$$n$$$ строчных латинских букв.</p><p>Сумма $$$n$$$ по всем наборам входных данных не превышает $$$1000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите MEX строки в отдельной строке.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 28 qaabzwsxedcrfvtgbyhnujmiklop 13 cleanairactbd 10 aannttoonn </pre></div><div class="output"><div class="title">Выходные данные</div><pre> ac f b </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:28: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:'8124c5e9ac2e16c7',t:'MTY5NjY2NzMzMi4yMDkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1200"]
1536C
1536
C
ru
C. Diluc и Kaeya
<div class="problem-statement"><div class="header"><div class="title">C. Diluc и Kaeya</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Магнат винодельческой империи в Мондштадте, непревзойденный во всех отношениях. Мыслитель из рыцарей Фавониуса с экзотической внешностью</span>}.</p><p>На этот раз братья имеют дело со странным куском дерева, помеченного их именами. Этот кусок дерева можно представить в виде строки из $$$n$$$ символов. Каждый символ — это либо <span class="tex-font-style-tt">'D'</span>, либо <span class="tex-font-style-tt">'K'</span>. Вы хотите сделать некоторое количество разрезов (возможно, $$$0$$$) в этой строке, разделив ее на несколько последовательных частей, каждая из которых имеет длину не менее $$$1$$$. Оба брата ведут себя достойно, поэтому они хотят разделить дерево как можно более равномерно. Они хотят знать, на какое максимальное число кусков можно разделить дерево, чтобы отношение числа символов <span class="tex-font-style-tt">'D'</span> и числа символов <span class="tex-font-style-tt">'K'</span> в каждом куске было одинаковым. </p><p>Kaeya, любознательный мыслитель, хотел бы знать решение сразу для нескольких сценариев. Он хочет узнать ответ для каждого <span class="tex-font-style-bf">префикса</span> данной строки. Помогите ему решить эту задачу!</p><p>Для строки мы определяем отношение как $$$a:b$$$, где <span class="tex-font-style-tt">'D'</span> встречается в ней $$$a$$$ раз, а <span class="tex-font-style-tt">'K'</span> встречается $$$b$$$ раз. Обратите внимание, что $$$a$$$ или $$$b$$$ могут быть равны $$$0$$$, но не оба. Отношения $$$a:b$$$ и $$$c:d$$$ считаются равными тогда и только тогда, когда $$$a\cdot d = b\cdot c$$$. </p><p>Например, для строки <span class="tex-font-style-tt">'DDD'</span> отношение будет $$$3:0$$$, для <span class="tex-font-style-tt">'DKD'</span> — $$$2:1$$$, для <span class="tex-font-style-tt">'DKK'</span> — $$$1:2$$$, а для <span class="tex-font-style-tt">'KKKKDD'</span> — $$$2:4$$$. Обратите внимание, что отношения двух последних строк равны между собой, но не равны отношениям первых двух строк.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит количество наборов входных данных $$$t$$$ ($$$1 \le t \le 1000$$$). Далее следует описание наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит целое число $$$n$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$) — длина дерева.</p><p>Вторая строка каждого набора входных данных содержит строку $$$s$$$ длиной $$$n$$$. Каждый символ $$$s$$$ будет либо <span class="tex-font-style-tt">'D'</span>, либо <span class="tex-font-style-tt">'K'</span>.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$5 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите $$$n$$$ целых чисел через пробел. $$$i$$$-е из этих чисел должно быть равно ответу для префикса $$$s_{1},s_{2},\dots,s_{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 3 DDK 6 DDDDDD 4 DKDK 1 D 9 DKDKDDDDK </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 1 1 2 3 4 5 6 1 1 1 2 1 1 1 1 2 1 2 1 1 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого набора входных данных нет способа разбить <span class="tex-font-style-tt">'D'</span> или <span class="tex-font-style-tt">'DDK'</span> на более чем один блок с равным отношением количеств <span class="tex-font-style-tt">'D'</span> и <span class="tex-font-style-tt">'K'</span>, в то время как <span class="tex-font-style-tt">'DD'</span> можно разбить на <span class="tex-font-style-tt">'D'</span> и <span class="tex-font-style-tt">'D'</span>.</p><p>Для второго набора входных данных, каждый префикс длины $$$i$$$ вы можете разделить на $$$i$$$ блоков <span class="tex-font-style-tt">'D'</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="cd1ee85f7993ab977b899655a42ed6b6"/> <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="c5b14aed5c3545d647c4685d950ef358bc98f539"/> <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='cd1ee85f7993ab977b899655a42ed6b6'>&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%2F1536%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='cd1ee85f7993ab977b899655a42ed6b6'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1536">Codeforces Round 724 (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='cd1ee85f7993ab977b899655a42ed6b6'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1536/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='cd1ee85f7993ab977b899655a42ed6b6'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1007471"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='cd1ee85f7993ab977b899655a42ed6b6'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1007471"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91438" title="Codeforces Round #724 (Rated for Div 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13818" resourceName="Codeforces Round #724 (Rated for Div 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/91520" title="Codeforces Round #724 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13842" resourceName="Codeforces Round #724 — 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/1536">Задачи</a></li> <li><a href="/contest/1536/submit">Отослать</a></li> <li><a href="/contest/1536/my">Мои посылки</a></li> <li><a href="/contest/1536/status">Статус</a></li> <li><a href="/contest/1536/hacks">Взломы</a></li> <li><a href="/contest/1536/room/1">Комната</a></li> <li><a href="/contest/1536/standings">Положение</a></li> <li><a href="/contest/1536/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_97c43f6ee017a6be22723dc690f316ca4717197f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. Diluc и Kaeya</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Магнат винодельческой империи в Мондштадте, непревзойденный во всех отношениях. Мыслитель из рыцарей Фавониуса с экзотической внешностью</span>}.</p><p>На этот раз братья имеют дело со странным куском дерева, помеченного их именами. Этот кусок дерева можно представить в виде строки из $$$n$$$ символов. Каждый символ — это либо <span class="tex-font-style-tt">'D'</span>, либо <span class="tex-font-style-tt">'K'</span>. Вы хотите сделать некоторое количество разрезов (возможно, $$$0$$$) в этой строке, разделив ее на несколько последовательных частей, каждая из которых имеет длину не менее $$$1$$$. Оба брата ведут себя достойно, поэтому они хотят разделить дерево как можно более равномерно. Они хотят знать, на какое максимальное число кусков можно разделить дерево, чтобы отношение числа символов <span class="tex-font-style-tt">'D'</span> и числа символов <span class="tex-font-style-tt">'K'</span> в каждом куске было одинаковым. </p><p>Kaeya, любознательный мыслитель, хотел бы знать решение сразу для нескольких сценариев. Он хочет узнать ответ для каждого <span class="tex-font-style-bf">префикса</span> данной строки. Помогите ему решить эту задачу!</p><p>Для строки мы определяем отношение как $$$a:b$$$, где <span class="tex-font-style-tt">'D'</span> встречается в ней $$$a$$$ раз, а <span class="tex-font-style-tt">'K'</span> встречается $$$b$$$ раз. Обратите внимание, что $$$a$$$ или $$$b$$$ могут быть равны $$$0$$$, но не оба. Отношения $$$a:b$$$ и $$$c:d$$$ считаются равными тогда и только тогда, когда $$$a\cdot d = b\cdot c$$$. </p><p>Например, для строки <span class="tex-font-style-tt">'DDD'</span> отношение будет $$$3:0$$$, для <span class="tex-font-style-tt">'DKD'</span> — $$$2:1$$$, для <span class="tex-font-style-tt">'DKK'</span> — $$$1:2$$$, а для <span class="tex-font-style-tt">'KKKKDD'</span> — $$$2:4$$$. Обратите внимание, что отношения двух последних строк равны между собой, но не равны отношениям первых двух строк.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит количество наборов входных данных $$$t$$$ ($$$1 \le t \le 1000$$$). Далее следует описание наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит целое число $$$n$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$) — длина дерева.</p><p>Вторая строка каждого набора входных данных содержит строку $$$s$$$ длиной $$$n$$$. Каждый символ $$$s$$$ будет либо <span class="tex-font-style-tt">'D'</span>, либо <span class="tex-font-style-tt">'K'</span>.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$5 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите $$$n$$$ целых чисел через пробел. $$$i$$$-е из этих чисел должно быть равно ответу для префикса $$$s_{1},s_{2},\dots,s_{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 3 DDK 6 DDDDDD 4 DKDK 1 D 9 DKDKDDDDK </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 1 1 2 3 4 5 6 1 1 1 2 1 1 1 1 2 1 2 1 1 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого набора входных данных нет способа разбить <span class="tex-font-style-tt">'D'</span> или <span class="tex-font-style-tt">'DDK'</span> на более чем один блок с равным отношением количеств <span class="tex-font-style-tt">'D'</span> и <span class="tex-font-style-tt">'K'</span>, в то время как <span class="tex-font-style-tt">'DD'</span> можно разбить на <span class="tex-font-style-tt">'D'</span> и <span class="tex-font-style-tt">'D'</span>.</p><p>Для второго набора входных данных, каждый префикс длины $$$i$$$ вы можете разделить на $$$i$$$ блоков <span class="tex-font-style-tt">'D'</span>.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:28: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:'8124c5f1feff7a71',t:'MTY5NjY2NzMzMy41MDQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\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.", "\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", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "\u0445\u044d\u0448\u0438", "*1500"]
1536D
1536
D
ru
D. Омкар и медианы
<div class="problem-statement"><div class="header"><div class="title">D. Омкар и медианы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>О-о-о! Рэй снова потерял свой массив! Однако Омкар может помочь, потому что он думает, что нашел <span class="tex-font-style-it">OmkArray</span> массива Рэя. <span class="tex-font-style-it">OmkArray</span> массива $$$a$$$ с элементами $$$a_1, a_2, \ldots, a_{2k-1}$$$ — это массив $$$b$$$ с элементами $$$b_1, b_2, \ldots, b_{k}$$$ такой, что $$$b_i$$$ равен медиане $$$a_1, a_2, \ldots, a_{2i-1}$$$ для всех $$$i$$$. Омкар нашел массив $$$b$$$ размера $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$-10^9 \leq b_i \leq 10^9$$$). Для этого массива $$$b$$$, Рэй хочет проверить утверждение Омкара и узнать, действительно ли $$$b$$$ является <span class="tex-font-style-it">OmkArray</span> некоторого массива $$$a$$$. Можете ли вы помочь Рэю?</p><p>Медиана набора чисел $$$a_1, a_2, \ldots, a_{2i-1}$$$ — это число $$$c_{i}$$$, где $$$c_{1}, c_{2}, \ldots, c_{2i-1}$$$ представляют собой $$$a_1, a_2, \ldots, a_{2i-1}$$$, отсортированные в неубывающем порядке. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — количество наборов входных данных. Далее следует описание наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит целое число $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — длину массива $$$b$$$.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$b_1, b_2, \ldots, b_n$$$ ($$$-10^9 \leq b_i \leq 10^9$$$) — элементы $$$b$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую <span class="tex-font-style-tt">YES</span>, если существует массив $$$a$$$ такой, что $$$b_i$$$ является медианой $$$a_1, a_2, \dots, a_{2i-1}$$$ для всех $$$i$$$, и <span class="tex-font-style-tt">NO</span> в противном случае. Регистр букв в <span class="tex-font-style-tt">YES</span> и <span class="tex-font-style-tt">NO</span> не имеет значения (поэтому <span class="tex-font-style-tt">yEs</span> и <span class="tex-font-style-tt">No</span> также будут приняты).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO YES NO YES YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 8 -8 2 -6 -5 -4 3 3 2 7 1 1 3 1 0 -2 -1 7 6 12 8 6 2 6 10 6 5 1 2 3 6 7 5 1 3 4 3 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO YES NO NO NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Во втором наборе входных данных первого примера массив $$$[4]$$$ даст OmkArray $$$[4]$$$, так как медиана первого элемента равна $$$4$$$.</p><p>В четвертом наборе входных данных первого примера массив $$$[3, 2, 5]$$$ даст OmkArray $$$[3, 3]$$$, так как медиана $$$3$$$ равна $$$3$$$, а медиана $$$2, 3, 5$$$ равна $$$3$$$.</p><p>В пятом наборе входных данных первого примера массив $$$[2, 1, 0, 3, 4, 4, 3]$$$ даст OmkArray $$$[2, 1, 2, 3]$$$, так как </p><ul> <li> медиана $$$2$$$ равна $$$2$$$ </li><li> медиана $$$0, 1, 2$$$ равна $$$1$$$ </li><li> медиана $$$0, 1, 2, 3, 4$$$ равна $$$2$$$ </li><li> и медиана $$$0, 1, 2, 3, 3, 4, 4$$$ равна $$$3$$$. </li></ul><p>Во втором наборе входных данных второй выборки массив $$$[1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5]$$$ даст OmkArray $$$[1, 1, 3, 1, 0, -2, -1]$$$, как </p><ul> <li> медиана $$$1$$$ равна $$$1$$$ </li><li> медиана из $$$0, 1, 4$$$ равна $$$1$$$ </li><li> медиана из $$$0, 1, 3, 4, 5$$$ равна $$$3$$$ </li><li> медиана $$$-2, -1, 0, 1, 3, 4, 5$$$ равна $$$1$$$ </li><li> медиана $$$-4, -2, -2, -2, 0, 1, 3, 4, 5$$$ равна $$$0$$$ </li><li> медиана $$$-4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5$$$ равна $$$-2$$$ </li><li> и медиана $$$-4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5$$$ равна $$$-1$$$ </li></ul><p>Для всех случаев, когда ответ <span class="tex-font-style-tt">NO</span>, можно доказать, что невозможно найти массив $$$a$$$ такой, что $$$b$$$ является Omkarray $$$a$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="8aaf1699d9ca26569e7fe11e3be10acc"/> <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="c5b14aed5c3545d647c4685d950ef358bc98f539"/> <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='8aaf1699d9ca26569e7fe11e3be10acc'>&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%2F1536%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='8aaf1699d9ca26569e7fe11e3be10acc'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1536">Codeforces Round 724 (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='8aaf1699d9ca26569e7fe11e3be10acc'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1536/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='8aaf1699d9ca26569e7fe11e3be10acc'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1007472"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8aaf1699d9ca26569e7fe11e3be10acc'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1007472"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91438" title="Codeforces Round #724 (Rated for Div 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13818" resourceName="Codeforces Round #724 (Rated for Div 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/91520" title="Codeforces Round #724 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13842" resourceName="Codeforces Round #724 — 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/1536">Задачи</a></li> <li><a href="/contest/1536/submit">Отослать</a></li> <li><a href="/contest/1536/my">Мои посылки</a></li> <li><a href="/contest/1536/status">Статус</a></li> <li><a href="/contest/1536/hacks">Взломы</a></li> <li><a href="/contest/1536/room/1">Комната</a></li> <li><a href="/contest/1536/standings">Положение</a></li> <li><a href="/contest/1536/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_01deff6ffc7e114dd79c1ea194dfd82f5a69e41b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Омкар и медианы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>О-о-о! Рэй снова потерял свой массив! Однако Омкар может помочь, потому что он думает, что нашел <span class="tex-font-style-it">OmkArray</span> массива Рэя. <span class="tex-font-style-it">OmkArray</span> массива $$$a$$$ с элементами $$$a_1, a_2, \ldots, a_{2k-1}$$$ — это массив $$$b$$$ с элементами $$$b_1, b_2, \ldots, b_{k}$$$ такой, что $$$b_i$$$ равен медиане $$$a_1, a_2, \ldots, a_{2i-1}$$$ для всех $$$i$$$. Омкар нашел массив $$$b$$$ размера $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$-10^9 \leq b_i \leq 10^9$$$). Для этого массива $$$b$$$, Рэй хочет проверить утверждение Омкара и узнать, действительно ли $$$b$$$ является <span class="tex-font-style-it">OmkArray</span> некоторого массива $$$a$$$. Можете ли вы помочь Рэю?</p><p>Медиана набора чисел $$$a_1, a_2, \ldots, a_{2i-1}$$$ — это число $$$c_{i}$$$, где $$$c_{1}, c_{2}, \ldots, c_{2i-1}$$$ представляют собой $$$a_1, a_2, \ldots, a_{2i-1}$$$, отсортированные в неубывающем порядке. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — количество наборов входных данных. Далее следует описание наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит целое число $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — длину массива $$$b$$$.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$b_1, b_2, \ldots, b_n$$$ ($$$-10^9 \leq b_i \leq 10^9$$$) — элементы $$$b$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую <span class="tex-font-style-tt">YES</span>, если существует массив $$$a$$$ такой, что $$$b_i$$$ является медианой $$$a_1, a_2, \dots, a_{2i-1}$$$ для всех $$$i$$$, и <span class="tex-font-style-tt">NO</span> в противном случае. Регистр букв в <span class="tex-font-style-tt">YES</span> и <span class="tex-font-style-tt">NO</span> не имеет значения (поэтому <span class="tex-font-style-tt">yEs</span> и <span class="tex-font-style-tt">No</span> также будут приняты).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO YES NO YES YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 8 -8 2 -6 -5 -4 3 3 2 7 1 1 3 1 0 -2 -1 7 6 12 8 6 2 6 10 6 5 1 2 3 6 7 5 1 3 4 3 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO YES NO NO NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Во втором наборе входных данных первого примера массив $$$[4]$$$ даст OmkArray $$$[4]$$$, так как медиана первого элемента равна $$$4$$$.</p><p>В четвертом наборе входных данных первого примера массив $$$[3, 2, 5]$$$ даст OmkArray $$$[3, 3]$$$, так как медиана $$$3$$$ равна $$$3$$$, а медиана $$$2, 3, 5$$$ равна $$$3$$$.</p><p>В пятом наборе входных данных первого примера массив $$$[2, 1, 0, 3, 4, 4, 3]$$$ даст OmkArray $$$[2, 1, 2, 3]$$$, так как </p><ul> <li> медиана $$$2$$$ равна $$$2$$$ </li><li> медиана $$$0, 1, 2$$$ равна $$$1$$$ </li><li> медиана $$$0, 1, 2, 3, 4$$$ равна $$$2$$$ </li><li> и медиана $$$0, 1, 2, 3, 3, 4, 4$$$ равна $$$3$$$. </li></ul><p>Во втором наборе входных данных второй выборки массив $$$[1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5]$$$ даст OmkArray $$$[1, 1, 3, 1, 0, -2, -1]$$$, как </p><ul> <li> медиана $$$1$$$ равна $$$1$$$ </li><li> медиана из $$$0, 1, 4$$$ равна $$$1$$$ </li><li> медиана из $$$0, 1, 3, 4, 5$$$ равна $$$3$$$ </li><li> медиана $$$-2, -1, 0, 1, 3, 4, 5$$$ равна $$$1$$$ </li><li> медиана $$$-4, -2, -2, -2, 0, 1, 3, 4, 5$$$ равна $$$0$$$ </li><li> медиана $$$-4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5$$$ равна $$$-2$$$ </li><li> и медиана $$$-4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5$$$ равна $$$-1$$$ </li></ul><p>Для всех случаев, когда ответ <span class="tex-font-style-tt">NO</span>, можно доказать, что невозможно найти массив $$$a$$$ такой, что $$$b$$$ является Omkarray $$$a$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:28: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:'8124c5fa1d249d93',t:'MTY5NjY2NzMzNC44OTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2000"]
1536E
1536
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>Последний присоединившийся последователь Омкара, Ajit, вошел в Священный лес. Ajit понимает, что лес Омкара — это таблица размером $$$n$$$ на $$$m$$$ ($$$1 \leq n, m \leq 2000$$$), состоящая из целых неотрицательных чисел. Поскольку лес благословлен Омкаром, он удовлетворяет некоторым особым условиям:</p><ol> <li> Для любых двух соседних по стороне клеток абсолютное значение разности чисел в них не превышает $$$1$$$. </li><li> Если число в какой-то клетке строго больше $$$0$$$, то оно должно быть строго больше, чем значение числа в <span class="tex-font-style-bf">по крайней мере одной</span> клетке, примыкающей к ней по стороне. </li></ol><p>К сожалению, Ajit еще не полностью достоин способностей Омкара. Он видит каждую клетку как "0" или "#". Если клетка обозначена как "0", то число в ней должно быть равно $$$0$$$. Иначе число в ней может быть любым неотрицательным целым числом.</p><p>Определите, сколько существует различных конфигураций элементов, при которых выполняются эти особые условия. Две конфигурации считаются различными, если существует хотя бы одна клетка такая, что числа, записанные в ней в этих конфигурациях, различны. Поскольку ответ может быть огромным, найдите ответ по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит количество наборов входных данных $$$t$$$ ($$$1 \leq t \leq 100$$$). Далее следует описание наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n, m \leq 2000, nm \geq 2$$$) — размеры леса.</p><p>Далее следуют $$$n$$$ строк, каждая из которых состоит из одной строки из $$$m$$$ символов. Каждый из этих символов является либо "0", либо "#".</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$2000$$$, а также сумма $$$m$$$ по всем наборам входных данных не превышает $$$2000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число: количество допустимых конфигураций по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 4 0000 00#0 0000 2 1 # # 1 2 ## 6 29 ############################# #000##0###0##0#0####0####000# #0#0##00#00##00####0#0###0#0# #0#0##0#0#0##00###00000##00## #000##0###0##0#0##0###0##0#0# ############################# </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 3 319908071 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого набора входных данных есть две допустимых конфигурации:</p><p>$$$0000\\ 0000\\ 0000$$$</p><p>и</p><p>$$$0000\\ 0010\\ 0000$$$</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="dbd53554210e4d759238fe841b3045a3"/> <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="c5b14aed5c3545d647c4685d950ef358bc98f539"/> <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='dbd53554210e4d759238fe841b3045a3'>&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%2F1536%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='dbd53554210e4d759238fe841b3045a3'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1536">Codeforces Round 724 (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='dbd53554210e4d759238fe841b3045a3'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1536/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='dbd53554210e4d759238fe841b3045a3'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1007473"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='dbd53554210e4d759238fe841b3045a3'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1007473"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91438" title="Codeforces Round #724 (Rated for Div 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13818" resourceName="Codeforces Round #724 (Rated for Div 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/91520" title="Codeforces Round #724 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13842" resourceName="Codeforces Round #724 — 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/1536">Задачи</a></li> <li><a href="/contest/1536/submit">Отослать</a></li> <li><a href="/contest/1536/my">Мои посылки</a></li> <li><a href="/contest/1536/status">Статус</a></li> <li><a href="/contest/1536/hacks">Взломы</a></li> <li><a href="/contest/1536/room/1">Комната</a></li> <li><a href="/contest/1536/standings">Положение</a></li> <li><a href="/contest/1536/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d1ce1eb26b4f308a701ead2e1b1df4d678a76c2a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Последний присоединившийся последователь Омкара, Ajit, вошел в Священный лес. Ajit понимает, что лес Омкара — это таблица размером $$$n$$$ на $$$m$$$ ($$$1 \leq n, m \leq 2000$$$), состоящая из целых неотрицательных чисел. Поскольку лес благословлен Омкаром, он удовлетворяет некоторым особым условиям:</p><ol> <li> Для любых двух соседних по стороне клеток абсолютное значение разности чисел в них не превышает $$$1$$$. </li><li> Если число в какой-то клетке строго больше $$$0$$$, то оно должно быть строго больше, чем значение числа в <span class="tex-font-style-bf">по крайней мере одной</span> клетке, примыкающей к ней по стороне. </li></ol><p>К сожалению, Ajit еще не полностью достоин способностей Омкара. Он видит каждую клетку как &quot;0&quot; или &quot;#&quot;. Если клетка обозначена как &quot;0&quot;, то число в ней должно быть равно $$$0$$$. Иначе число в ней может быть любым неотрицательным целым числом.</p><p>Определите, сколько существует различных конфигураций элементов, при которых выполняются эти особые условия. Две конфигурации считаются различными, если существует хотя бы одна клетка такая, что числа, записанные в ней в этих конфигурациях, различны. Поскольку ответ может быть огромным, найдите ответ по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит количество наборов входных данных $$$t$$$ ($$$1 \leq t \leq 100$$$). Далее следует описание наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n, m \leq 2000, nm \geq 2$$$) — размеры леса.</p><p>Далее следуют $$$n$$$ строк, каждая из которых состоит из одной строки из $$$m$$$ символов. Каждый из этих символов является либо &quot;0&quot;, либо &quot;#&quot;.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$2000$$$, а также сумма $$$m$$$ по всем наборам входных данных не превышает $$$2000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число: количество допустимых конфигураций по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 4 0000 00#0 0000 2 1 # # 1 2 ## 6 29 ############################# #000##0###0##0#0####0####000# #0#0##00#00##00####0#0###0#0# #0#0##0#0#0##00###00000##00## #000##0###0##0#0##0###0##0#0# ############################# </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 3 319908071 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого набора входных данных есть две допустимых конфигурации:</p><p>$$$0000\\ 0000\\ 0000$$$</p><p>и</p><p>$$$0000\\ 0010\\ 0000$$$</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:28: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:'8124c602adc67b5f',t:'MTY5NjY2NzMzNi4yNTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u041a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438 \u043d\u0430 \u0433\u0440\u0430\u0444\u0430\u0445", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*2300"]
1536F
1536
F
ru
F. Омкар и Акмар
<div class="problem-statement"><div class="header"><div class="title">F. Омкар и Акмар</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Омкар и Акмар играют в игру на круговой доске с $$$n$$$ ($$$2 \leq n \leq 10^6$$$) клетками. Клетки пронумерованы от $$$1$$$ до $$$n$$$, для каждой $$$i$$$ ($$$1 \leq i \leq n-1$$$) клетка $$$i$$$ соседствует с клеткой $$$i+1$$$, а клетка $$$1$$$ соседствует с клеткой $$$n$$$. Изначально каждая клетка пуста.</p><p>Омкар и Акмар по очереди выкладывают на доску букву A или B, причем Акмар ходит первым. Буква должна быть помещена на пустую клетку. Кроме того, буква не может быть помещена в такую клетку, что соседняя клетка содержит ту же букву. </p><p>Игрок проигрывает, когда наступает его очередь и больше нет допустимых ходов.</p><p>Выведите количество возможных различных игр, в которых оба игрока играют оптимально по модулю $$$10^9+7$$$. Обратите внимание, что мы рассматриваем только те партии, в которых кто-то из игроков проиграл, и не осталось ни одного допустимого хода.</p><p>Две игры считаются разными, если количества ходов в них отличаются, или на каком-то ходу буква или номер клетки, на которую ставится буква, были разными.</p><p>Ход считается оптимальным, если он максимизирует шансы игрока на победу, предполагая, что другой игрок также играет оптимально. Более формально, если игрок, чья очередь ходить, имеет выигрышную стратегию, он должен сделать ход, после которого у него останется выигрышная стратегия. Если же у него ее нет, то он может сделать любой ход.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка будет содержать целое число $$$n$$$ ($$$2 \leq n \leq 10^6$$$) — количество клеток на доске.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, — количество возможных различных игр, в которых оба игрока играют оптимально по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 69420 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 629909355 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 42069 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 675837193 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере первый игрок имеет $$$4$$$ возможных хода. Независимо от того, как ходит первый игрок, у второго игрока есть ровно $$$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="37256640398f3e546aa282d50e4dbcef"/> <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="c5b14aed5c3545d647c4685d950ef358bc98f539"/> <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='37256640398f3e546aa282d50e4dbcef'>&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%2F1536%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='37256640398f3e546aa282d50e4dbcef'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1536">Codeforces Round 724 (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='37256640398f3e546aa282d50e4dbcef'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1536/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Суффиксные массивы, деревья и автоматы"> строковые суфф. структуры </span> </div> <div class="roundbox borderTopRound 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='37256640398f3e546aa282d50e4dbcef'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1007474"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='37256640398f3e546aa282d50e4dbcef'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1007474"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91438" title="Codeforces Round #724 (Rated for Div 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13818" resourceName="Codeforces Round #724 (Rated for Div 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/91520" title="Codeforces Round #724 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13842" resourceName="Codeforces Round #724 — 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/1536">Задачи</a></li> <li><a href="/contest/1536/submit">Отослать</a></li> <li><a href="/contest/1536/my">Мои посылки</a></li> <li><a href="/contest/1536/status">Статус</a></li> <li><a href="/contest/1536/hacks">Взломы</a></li> <li><a href="/contest/1536/room/1">Комната</a></li> <li><a href="/contest/1536/standings">Положение</a></li> <li><a href="/contest/1536/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_5135a00e80777a0c9c1c1ad3c0f92685d559fcf5"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Омкар и Акмар</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Омкар и Акмар играют в игру на круговой доске с $$$n$$$ ($$$2 \leq n \leq 10^6$$$) клетками. Клетки пронумерованы от $$$1$$$ до $$$n$$$, для каждой $$$i$$$ ($$$1 \leq i \leq n-1$$$) клетка $$$i$$$ соседствует с клеткой $$$i+1$$$, а клетка $$$1$$$ соседствует с клеткой $$$n$$$. Изначально каждая клетка пуста.</p><p>Омкар и Акмар по очереди выкладывают на доску букву A или B, причем Акмар ходит первым. Буква должна быть помещена на пустую клетку. Кроме того, буква не может быть помещена в такую клетку, что соседняя клетка содержит ту же букву. </p><p>Игрок проигрывает, когда наступает его очередь и больше нет допустимых ходов.</p><p>Выведите количество возможных различных игр, в которых оба игрока играют оптимально по модулю $$$10^9+7$$$. Обратите внимание, что мы рассматриваем только те партии, в которых кто-то из игроков проиграл, и не осталось ни одного допустимого хода.</p><p>Две игры считаются разными, если количества ходов в них отличаются, или на каком-то ходу буква или номер клетки, на которую ставится буква, были разными.</p><p>Ход считается оптимальным, если он максимизирует шансы игрока на победу, предполагая, что другой игрок также играет оптимально. Более формально, если игрок, чья очередь ходить, имеет выигрышную стратегию, он должен сделать ход, после которого у него останется выигрышная стратегия. Если же у него ее нет, то он может сделать любой ход.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка будет содержать целое число $$$n$$$ ($$$2 \leq n \leq 10^6$$$) — количество клеток на доске.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, — количество возможных различных игр, в которых оба игрока играют оптимально по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 69420 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 629909355 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 42069 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 675837193 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере первый игрок имеет $$$4$$$ возможных хода. Независимо от того, как ходит первый игрок, у второго игрока есть ровно $$$1$$$ возможный ход, поэтому существует $$$4$$$ возможных игры.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:28: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:'8124c60b4b2c9d51',t:'MTY5NjY2NzMzNy42OTAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\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\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u0418\u0433\u0440\u044b, \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0428\u043f\u0440\u0430\u0433\u0430-\u0413\u0440\u0430\u043d\u0434\u0438", "\u041a\u0438\u0442\u0430\u0439\u0441\u043a\u0430\u044f \u0442\u0435\u043e\u0440\u0435\u043c\u0430 \u043e\u0431 \u043e\u0441\u0442\u0430\u0442\u043a\u0430\u0445, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u0413\u0430\u0440\u043d\u0435\u0440\u0430", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u043c\u0430\u0441\u0441\u0438\u0432\u044b, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u0438 \u0430\u0432\u0442\u043e\u043c\u0430\u0442\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["meet-in-the-middle", "\u0431\u043f\u0444", "\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u0438\u0433\u0440\u044b", "\u043a\u0438\u0442\u0430\u0439\u0441\u043a\u0430\u044f \u0442\u0435\u043e\u0440\u0435\u043c\u0430 \u043e\u0431 \u043e\u0441\u0442\u0430\u0442\u043a\u0430\u0445", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0441\u0442\u0440\u043e\u043a\u043e\u0432\u044b\u0435 \u0441\u0443\u0444\u0444. \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b", "*2600"]
1537A
1537
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>Массив $$$b$$$ длины $$$k$$$ называется хорошим, если его среднее арифметическое равно $$$1$$$. Более формально, если $$$$$$\frac{b_1 + \cdots + b_k}{k}=1.$$$$$$</p><p>Обратите внимание, что значение $$$\frac{b_1+\cdots+b_k}{k}$$$ не округляется в большую или меньшую сторону. Например, массив $$$[1,1,1,2]$$$ имеет среднее арифметическое $$$1.25$$$, а не равно $$$1$$$.</p><p>Вам дан массив $$$a$$$ из $$$n$$$ целых чисел. За одну операцию вы можете добавить в конец массива любое <span class="tex-font-style-bf">неотрицательное</span> целое число. Какое минимальное количество операций требуется для того, чтобы массив стал хорошим?</p><p>Можно показать, что этого всегда можно добиться за конечное число операций.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 1000$$$) — количество наборов входных данных. Затем следуют $$$t$$$ наборов входных данных.</p><p>Первая строка каждого тестового случая содержит одно целое число $$$n$$$ ($$$1 \leq n \leq 50$$$) — длину исходного массива $$$a$$$.</p><p>Вторая строка каждого теста содержит $$$n$$$ целых чисел $$$a_1,\ldots,a_n$$$ ($$$-10^4\leq a_i \leq 10^4$$$) — элементы массива.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — минимальное количество неотрицательных целых чисел, которые нужно добавить к массиву, чтобы его среднее арифметическое стало равно ровно $$$1$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 1 1 2 1 2 4 8 4 6 2 1 -2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 16 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных нам не нужно добавлять ни одного элемента, потому что среднее арифметическое массива уже равно $$$1$$$, поэтому ответ — $$$0$$$.</p><p>Во втором наборе входных данных среднее арифметическое изначально не равно $$$1$$$, поэтому нам нужно добавить еще хотя бы одно число. Если мы добавим $$$0$$$, то среднее арифметическое всего массива станет $$$1$$$, поэтому ответ — $$$1$$$.</p><p>В третьем наборе входных данных минимальное количество элементов, которые необходимо добавить, составляет $$$16$$$, так как добавлять можно только неотрицательные целые числа.</p><p>В четвертом наборе входных данных мы можем добавить одно целое число $$$4$$$. Среднее арифметическое становится $$$\frac{-2+4}{2}$$$, что равно $$$1$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="955655300b2471cdd3f5c0218ba45360"/> <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="25f0f3ba0917aa9b09d150bb9b22b6ff3edf1109"/> <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='955655300b2471cdd3f5c0218ba45360'>&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%2F1537%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='955655300b2471cdd3f5c0218ba45360'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1537">Codeforces Round 726 (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='955655300b2471cdd3f5c0218ba45360'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1537/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *800 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='955655300b2471cdd3f5c0218ba45360'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1020032"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='955655300b2471cdd3f5c0218ba45360'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1020032"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91835" title="Codeforces Round #726 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13904" resourceName="Codeforces Round #726 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/91381" title="Codeforces Round #726 (Div.2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13907" resourceName="Codeforces Round #726 (Div.2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1537">Задачи</a></li> <li><a href="/contest/1537/submit">Отослать</a></li> <li><a href="/contest/1537/my">Мои посылки</a></li> <li><a href="/contest/1537/status">Статус</a></li> <li><a href="/contest/1537/hacks">Взломы</a></li> <li><a href="/contest/1537/room/1">Комната</a></li> <li><a href="/contest/1537/standings">Положение</a></li> <li><a href="/contest/1537/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_6e4235e3367b7b2a25e3cf51f896e3a94acdff1d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Массив $$$b$$$ длины $$$k$$$ называется хорошим, если его среднее арифметическое равно $$$1$$$. Более формально, если $$$$$$\frac{b_1 + \cdots + b_k}{k}=1.$$$$$$</p><p>Обратите внимание, что значение $$$\frac{b_1+\cdots+b_k}{k}$$$ не округляется в большую или меньшую сторону. Например, массив $$$[1,1,1,2]$$$ имеет среднее арифметическое $$$1.25$$$, а не равно $$$1$$$.</p><p>Вам дан массив $$$a$$$ из $$$n$$$ целых чисел. За одну операцию вы можете добавить в конец массива любое <span class="tex-font-style-bf">неотрицательное</span> целое число. Какое минимальное количество операций требуется для того, чтобы массив стал хорошим?</p><p>Можно показать, что этого всегда можно добиться за конечное число операций.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 1000$$$) — количество наборов входных данных. Затем следуют $$$t$$$ наборов входных данных.</p><p>Первая строка каждого тестового случая содержит одно целое число $$$n$$$ ($$$1 \leq n \leq 50$$$) — длину исходного массива $$$a$$$.</p><p>Вторая строка каждого теста содержит $$$n$$$ целых чисел $$$a_1,\ldots,a_n$$$ ($$$-10^4\leq a_i \leq 10^4$$$) — элементы массива.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — минимальное количество неотрицательных целых чисел, которые нужно добавить к массиву, чтобы его среднее арифметическое стало равно ровно $$$1$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 1 1 2 1 2 4 8 4 6 2 1 -2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 16 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных нам не нужно добавлять ни одного элемента, потому что среднее арифметическое массива уже равно $$$1$$$, поэтому ответ — $$$0$$$.</p><p>Во втором наборе входных данных среднее арифметическое изначально не равно $$$1$$$, поэтому нам нужно добавить еще хотя бы одно число. Если мы добавим $$$0$$$, то среднее арифметическое всего массива станет $$$1$$$, поэтому ответ — $$$1$$$.</p><p>В третьем наборе входных данных минимальное количество элементов, которые необходимо добавить, составляет $$$16$$$, так как добавлять можно только неотрицательные целые числа.</p><p>В четвертом наборе входных данных мы можем добавить одно целое число $$$4$$$. Среднее арифметическое становится $$$\frac{-2+4}{2}$$$, что равно $$$1$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:28: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:'8124c6144f681667',t:'MTY5NjY2NzMzOS4xMTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*800"]
1537B
1537
B
ru
B. Плохой мальчик
<div class="problem-statement"><div class="header"><div class="title">B. Плохой мальчик</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Райли — очень плохой мальчик, но в то же время он мастер йо-йо. Поэтому он решил использовать свои навыки йо-йо, чтобы досадить своему другу Антону.</p><p>Комната Антона может быть представлена в виде сетки с $$$n$$$ строк и $$$m$$$ столбцов. Пусть $$$(i, j)$$$ обозначает клетку в строке $$$i$$$ и столбце $$$j$$$. В настоящее время Антон стоит в клетке $$$(i, j)$$$ своей комнаты. Чтобы досадить Антону, Райли решил бросить ровно <span class="tex-font-style-bf">два</span> йо-йо в клетки комнаты (они могут находиться в одной клетке).</p><p>Поскольку Антону не нравятся йо-йо, брошенные на пол, он должен поднять оба йо-йо и вернуться в исходную клетку. Расстояние, пройденное Антоном — это кратчайший путь, который проходит через позиции обоих йо-йо и возвращается в $$$(i, j)$$$, если можно проходить только в соседние по стороне клетки. То есть, если он находится в клетке $$$(x, y)$$$, то за один шаг (если клетка с такими координатами существует) он может попасть в одну из клеток $$$(x + 1, y)$$$, $$$(x - 1, y)$$$, $$$(x, y + 1)$$$ и $$$(x, y - 1)$$$.</p><p>Райли размышляет, куда ему бросить эти два йо-йо, чтобы расстояние, пройденное Антоном, было <span class="tex-font-style-bf">максимальным</span>. Но поскольку он очень занят, он попросил вас помочь ему.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — количество наборов входных данных. Затем следуют $$$t$$$ наборов входных данных.</p><p>Единственная строка каждого набора входных данных содержит четыре целых числа $$$n$$$, $$$m$$$, $$$i$$$, $$$j$$$ ($$$1 \leq n, m \leq 10^9$$$, $$$1\le i\le n$$$, $$$1\le j\le m$$$) — размеры комнаты и клетки, на которой в данный момент стоит Антон.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите четыре целых числа $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \leq x_1, x_2 \leq n$$$, $$$1\le y_1, y_2\le m$$$) — координаты, куда должны быть брошены два йо-йо. Они будут брошены в координаты $$$(x_1,y_1)$$$ и $$$(x_2,y_2)$$$.</p><p>Если ответов несколько, вы можете вывести любой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 2 3 1 1 4 4 1 2 3 5 2 2 5 1 2 1 3 1 3 1 1 1 1 1 1000000000 1000000000 1000000000 50 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 2 3 4 1 4 4 3 1 1 5 5 1 1 1 1 1 2 1 1 1 1 1 50 1 1 1000000000 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Вот визуализация первого набора входных данных. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/9f627c5459503105f9350b85dd766525751f357c.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="771e0201ded2ee9d1172f7089e06e01b"/> <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="25f0f3ba0917aa9b09d150bb9b22b6ff3edf1109"/> <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='771e0201ded2ee9d1172f7089e06e01b'>&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%2F1537%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='771e0201ded2ee9d1172f7089e06e01b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1537">Codeforces Round 726 (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='771e0201ded2ee9d1172f7089e06e01b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1537/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='771e0201ded2ee9d1172f7089e06e01b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1020033"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='771e0201ded2ee9d1172f7089e06e01b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1020033"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91835" title="Codeforces Round #726 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13904" resourceName="Codeforces Round #726 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/91381" title="Codeforces Round #726 (Div.2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13907" resourceName="Codeforces Round #726 (Div.2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1537">Задачи</a></li> <li><a href="/contest/1537/submit">Отослать</a></li> <li><a href="/contest/1537/my">Мои посылки</a></li> <li><a href="/contest/1537/status">Статус</a></li> <li><a href="/contest/1537/hacks">Взломы</a></li> <li><a href="/contest/1537/room/1">Комната</a></li> <li><a href="/contest/1537/standings">Положение</a></li> <li><a href="/contest/1537/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_da2b5aec36e038542a80fc657dccb5837487efa2"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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><p>Комната Антона может быть представлена в виде сетки с $$$n$$$ строк и $$$m$$$ столбцов. Пусть $$$(i, j)$$$ обозначает клетку в строке $$$i$$$ и столбце $$$j$$$. В настоящее время Антон стоит в клетке $$$(i, j)$$$ своей комнаты. Чтобы досадить Антону, Райли решил бросить ровно <span class="tex-font-style-bf">два</span> йо-йо в клетки комнаты (они могут находиться в одной клетке).</p><p>Поскольку Антону не нравятся йо-йо, брошенные на пол, он должен поднять оба йо-йо и вернуться в исходную клетку. Расстояние, пройденное Антоном — это кратчайший путь, который проходит через позиции обоих йо-йо и возвращается в $$$(i, j)$$$, если можно проходить только в соседние по стороне клетки. То есть, если он находится в клетке $$$(x, y)$$$, то за один шаг (если клетка с такими координатами существует) он может попасть в одну из клеток $$$(x + 1, y)$$$, $$$(x - 1, y)$$$, $$$(x, y + 1)$$$ и $$$(x, y - 1)$$$.</p><p>Райли размышляет, куда ему бросить эти два йо-йо, чтобы расстояние, пройденное Антоном, было <span class="tex-font-style-bf">максимальным</span>. Но поскольку он очень занят, он попросил вас помочь ему.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — количество наборов входных данных. Затем следуют $$$t$$$ наборов входных данных.</p><p>Единственная строка каждого набора входных данных содержит четыре целых числа $$$n$$$, $$$m$$$, $$$i$$$, $$$j$$$ ($$$1 \leq n, m \leq 10^9$$$, $$$1\le i\le n$$$, $$$1\le j\le m$$$) — размеры комнаты и клетки, на которой в данный момент стоит Антон.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите четыре целых числа $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \leq x_1, x_2 \leq n$$$, $$$1\le y_1, y_2\le m$$$) — координаты, куда должны быть брошены два йо-йо. Они будут брошены в координаты $$$(x_1,y_1)$$$ и $$$(x_2,y_2)$$$.</p><p>Если ответов несколько, вы можете вывести любой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 2 3 1 1 4 4 1 2 3 5 2 2 5 1 2 1 3 1 3 1 1 1 1 1 1000000000 1000000000 1000000000 50 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 2 3 4 1 4 4 3 1 1 5 5 1 1 1 1 1 2 1 1 1 1 1 50 1 1 1000000000 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Вот визуализация первого набора входных данных. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/9f627c5459503105f9350b85dd766525751f357c.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c61d4e209d4f',t:'MTY5NjY2NzM0MC40NjAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*900"]
1537C
1537
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$$$ высот гор, и вы хотите расположить эти высоты так, чтобы абсолютная разность между высотами первой и последней гор была как можно меньше. </p><p>Кроме того, вы хотите сделать игру сложной, а поскольку идти в гору или по равнине сложнее, чем спускаться по склону, то сложность уровня будет равна количеству гор $$$i$$$ ($$$1 \leq i &lt; n$$$) таких, что $$$h_i \leq h_{i+1}$$$, где $$$h_i$$$ — высота $$$i$$$-й горы. Вы не хотите потратить впустую ни одну из смоделированных гор, поэтому должны использовать их все. </p><p>Из всех вариантов, минимизирующих $$$|h_1-h_n|$$$, найдите самый сложный. Если существует несколько порядков, удовлетворяющих этим требованиям, вы можете найти любой.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка будет содержать одно целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество наборов входных данных. Затем следуют $$$t$$$ наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$) — количество гор.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$h_1,\ldots,h_n$$$ ($$$1 \leq h_i \leq 10^9$$$), где $$$h_i$$$ — высота $$$i$$$-й горы.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите $$$n$$$ целых чисел — заданные высоты в порядке, который максимизирует сложность уровня среди всех порядков, минимизирующих $$$|h_1-h_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> 2 4 4 2 1 2 2 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 4 1 2 1 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных:</p><p>Игрок начинает с высоты $$$2$$$, затем поднимается на высоту $$$4$$$, увеличивая сложность на $$$1$$$. После этого он спускается на высоту $$$1$$$, и сложность не меняется, потому что он спускается вниз. Наконец, игрок поднимется на высоту $$$2$$$, и сложность увеличится на $$$1$$$. Абсолютная разность между начальной и конечной высотой равна $$$0$$$, а следовательно минимальна. Трудность максимальна при данных условиях.</p><p>Во втором наборе входных данных:</p><p>Игрок начинает с высоты $$$1$$$, затем поднимается до высоты $$$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="0247fd754063dc477ae3ea1e93c01655"/> <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="25f0f3ba0917aa9b09d150bb9b22b6ff3edf1109"/> <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='0247fd754063dc477ae3ea1e93c01655'>&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%2F1537%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='0247fd754063dc477ae3ea1e93c01655'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1537">Codeforces Round 726 (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='0247fd754063dc477ae3ea1e93c01655'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1537/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *1200 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0247fd754063dc477ae3ea1e93c01655'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1020034"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0247fd754063dc477ae3ea1e93c01655'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1020034"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91835" title="Codeforces Round #726 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13904" resourceName="Codeforces Round #726 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/91381" title="Codeforces Round #726 (Div.2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13907" resourceName="Codeforces Round #726 (Div.2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1537">Задачи</a></li> <li><a href="/contest/1537/submit">Отослать</a></li> <li><a href="/contest/1537/my">Мои посылки</a></li> <li><a href="/contest/1537/status">Статус</a></li> <li><a href="/contest/1537/hacks">Взломы</a></li> <li><a href="/contest/1537/room/1">Комната</a></li> <li><a href="/contest/1537/standings">Положение</a></li> <li><a href="/contest/1537/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9a13298ea22300b15dd87bc0e81ab91757f2a570"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ высот гор, и вы хотите расположить эти высоты так, чтобы абсолютная разность между высотами первой и последней гор была как можно меньше. </p><p>Кроме того, вы хотите сделать игру сложной, а поскольку идти в гору или по равнине сложнее, чем спускаться по склону, то сложность уровня будет равна количеству гор $$$i$$$ ($$$1 \leq i &lt; n$$$) таких, что $$$h_i \leq h_{i+1}$$$, где $$$h_i$$$ — высота $$$i$$$-й горы. Вы не хотите потратить впустую ни одну из смоделированных гор, поэтому должны использовать их все. </p><p>Из всех вариантов, минимизирующих $$$|h_1-h_n|$$$, найдите самый сложный. Если существует несколько порядков, удовлетворяющих этим требованиям, вы можете найти любой.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка будет содержать одно целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество наборов входных данных. Затем следуют $$$t$$$ наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$) — количество гор.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$h_1,\ldots,h_n$$$ ($$$1 \leq h_i \leq 10^9$$$), где $$$h_i$$$ — высота $$$i$$$-й горы.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите $$$n$$$ целых чисел — заданные высоты в порядке, который максимизирует сложность уровня среди всех порядков, минимизирующих $$$|h_1-h_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> 2 4 4 2 1 2 2 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 4 1 2 1 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных:</p><p>Игрок начинает с высоты $$$2$$$, затем поднимается на высоту $$$4$$$, увеличивая сложность на $$$1$$$. После этого он спускается на высоту $$$1$$$, и сложность не меняется, потому что он спускается вниз. Наконец, игрок поднимется на высоту $$$2$$$, и сложность увеличится на $$$1$$$. Абсолютная разность между начальной и конечной высотой равна $$$0$$$, а следовательно минимальна. Трудность максимальна при данных условиях.</p><p>Во втором наборе входных данных:</p><p>Игрок начинает с высоты $$$1$$$, затем поднимается до высоты $$$3$$$, увеличивая сложность на $$$1$$$. Абсолютная разниость между начальной и конечной высотой равна $$$2$$$ и она минимально возможная, так как это единственные высоты. Трудность максимальна.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c625983f3a65',t:'MTY5NjY2NzM0MS44MDEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1200"]
1537D
1537
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$$$ и поочередно выполняют над ним операции. В свой игрок может вычесть из $$$n$$$ один из его делителей, который не равен $$$1$$$ или $$$n$$$. Игрок, который не может сделать ход в свой ход, проигрывает. Алиса всегда ходит первой.</p><p>Обратите внимание, что в каждый ход они вычитают делитель <span class="tex-font-style-bf">текущего</span> числа.</p><p>Вам предлагается выяснить, кто победит в игре, если оба игрока будут играть оптимально.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — количество наборов входных данных. Затем следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор входных данных содержит одно целое число $$$n$$$ ($$$1 \leq n \leq 10^9$$$) — начальное число.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">Alice</span>», если Алиса выиграет игру, или «<span class="tex-font-style-tt">Bob</span>», если выиграет Боб, если оба игрока играют оптимально.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 1 4 12 69 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Bob Alice Alice Bob </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных игра немедленно заканчивается, потому что Алиса не может сделать ход.</p><p>Во втором наборе входных данных Алиса может вычесть $$$2$$$, получив $$$n = 2$$$, тогда Боб не сможет сделать ход, и Алиса выиграет.</p><p>В третьем наборе входных данных Алиса может вычесть $$$3$$$, получив $$$n = 9$$$. Единственный ход Боба — вычесть $$$3$$$ и сделать $$$n = 6$$$. Теперь Алиса может снова вычесть $$$3$$$ и получить $$$n = 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="51a32283097baa545ec42fa27366dedd"/> <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="25f0f3ba0917aa9b09d150bb9b22b6ff3edf1109"/> <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='51a32283097baa545ec42fa27366dedd'>&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%2F1537%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='51a32283097baa545ec42fa27366dedd'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1537">Codeforces Round 726 (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='51a32283097baa545ec42fa27366dedd'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1537/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='51a32283097baa545ec42fa27366dedd'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1020035"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='51a32283097baa545ec42fa27366dedd'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1020035"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91835" title="Codeforces Round #726 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13904" resourceName="Codeforces Round #726 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/91381" title="Codeforces Round #726 (Div.2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13907" resourceName="Codeforces Round #726 (Div.2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1537">Задачи</a></li> <li><a href="/contest/1537/submit">Отослать</a></li> <li><a href="/contest/1537/my">Мои посылки</a></li> <li><a href="/contest/1537/status">Статус</a></li> <li><a href="/contest/1537/hacks">Взломы</a></li> <li><a href="/contest/1537/room/1">Комната</a></li> <li><a href="/contest/1537/standings">Положение</a></li> <li><a href="/contest/1537/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f787b903c18a673ce9e3e1636bd4b03bda8808ed"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ и поочередно выполняют над ним операции. В свой игрок может вычесть из $$$n$$$ один из его делителей, который не равен $$$1$$$ или $$$n$$$. Игрок, который не может сделать ход в свой ход, проигрывает. Алиса всегда ходит первой.</p><p>Обратите внимание, что в каждый ход они вычитают делитель <span class="tex-font-style-bf">текущего</span> числа.</p><p>Вам предлагается выяснить, кто победит в игре, если оба игрока будут играть оптимально.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — количество наборов входных данных. Затем следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор входных данных содержит одно целое число $$$n$$$ ($$$1 \leq n \leq 10^9$$$) — начальное число.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">Alice</span>», если Алиса выиграет игру, или «<span class="tex-font-style-tt">Bob</span>», если выиграет Боб, если оба игрока играют оптимально.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 1 4 12 69 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Bob Alice Alice Bob </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных игра немедленно заканчивается, потому что Алиса не может сделать ход.</p><p>Во втором наборе входных данных Алиса может вычесть $$$2$$$, получив $$$n = 2$$$, тогда Боб не сможет сделать ход, и Алиса выиграет.</p><p>В третьем наборе входных данных Алиса может вычесть $$$3$$$, получив $$$n = 9$$$. Единственный ход Боба — вычесть $$$3$$$ и сделать $$$n = 6$$$. Теперь Алиса может снова вычесть $$$3$$$ и получить $$$n = 3$$$. После этого Боб не может сделать ход, и Алиса выигрывает.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c62def663a5f',t:'MTY5NjY2NzM0My4wOTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u0433\u0440\u044b, \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0428\u043f\u0440\u0430\u0433\u0430-\u0413\u0440\u0430\u043d\u0434\u0438", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0438\u0433\u0440\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1700"]
1537E1
1537
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">Это простая версия задачи. Единственное отличие — это ограничения на $$$n$$$ и $$$k$$$. Вы можете делать взломы, только если все версии задачи решены</span>.</p><p>У вас есть строка $$$s$$$, и вы можете выполнять над ней два типа операций: </p><ul> <li> Удалить последний символ строки. </li><li> Дублировать строку: $$$s:=s+s$$$, где $$$+$$$ обозначает конкатенацию. </li></ul><p>Вы можете использовать каждую операцию любое количество раз (возможно, ни одного).</p><p>Ваша задача — найти лексикографически наименьшую строку длины ровно $$$k$$$, которую можно получить, выполнив эти операции над строкой $$$s$$$.</p><p>Строка $$$a$$$ лексикографически меньше строки $$$b$$$ тогда и только тогда, когда выполняется одно из следующих условий:</p><ul> <li> $$$a$$$ является префиксом $$$b$$$, но $$$a\ne b$$$; </li><li> В первой позиции, где $$$a$$$ и $$$b$$$ отличаются, строка $$$a$$$ имеет букву, которая появляется раньше в алфавите, чем соответствующая буква в $$$b$$$. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$, $$$k$$$ ($$$1 \leq n, k \leq 5000$$$) — длину исходной строки $$$s$$$ и длину желаемой строки.</p><p>Вторая строка содержит строку $$$s$$$, состоящую из $$$n$$$ строчных английских букв.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите лексикографически наименьшую строку длины $$$k$$$, которая может быть получена путем выполнения операций над строкой $$$s$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 8 16 dbcadabc </pre></div><div class="output"><div class="title">Выходные данные</div><pre> dbcadabcdbcadabc </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 5 abcd </pre></div><div class="output"><div class="title">Выходные данные</div><pre> aaaaa </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте оптимально сделать одно дублирование: «<span class="tex-font-style-tt">dbcadabc</span>» $$$\to$$$ «<span class="tex-font-style-tt">dbcadabcdbcadabc</span>».</p><p>Во втором тесте оптимально удалить последние $$$3$$$ символа, затем продублировать строку $$$3$$$ раза, затем удалить последние $$$3$$$ символов, чтобы строка имела длину $$$k$$$.</p><p>«<span class="tex-font-style-tt">abcd</span>» $$$\to$$$ «<span class="tex-font-style-tt">abc</span>» $$$\to$$$ «<span class="tex-font-style-tt">ab</span>» $$$\to$$$ «<span class="tex-font-style-tt">a</span>» $$$\to$$$ «<span class="tex-font-style-tt">aa</span>» $$$\to$$$ «<span class="tex-font-style-tt">aaaa</span>» $$$\to$$$ «<span class="tex-font-style-tt">aaaa</span>» $$$\to$$$ «<span class="tex-font-style-tt">aaaa</span>» $$$\to$$$ «<span class="tex-font-style-tt">aaaa</span>» $$$\to$$$ «<span class="tex-font-style-tt">aaaa</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="1c9eab5e7cd5715a94fc05dd72acd580"/> <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="25f0f3ba0917aa9b09d150bb9b22b6ff3edf1109"/> <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='1c9eab5e7cd5715a94fc05dd72acd580'>&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%2F1537%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='1c9eab5e7cd5715a94fc05dd72acd580'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1537">Codeforces Round 726 (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='1c9eab5e7cd5715a94fc05dd72acd580'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1537/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Префикс- и 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="Сложность"> *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='1c9eab5e7cd5715a94fc05dd72acd580'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1020036"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1c9eab5e7cd5715a94fc05dd72acd580'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1020036"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91835" title="Codeforces Round #726 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13904" resourceName="Codeforces Round #726 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/91381" title="Codeforces Round #726 (Div.2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13907" resourceName="Codeforces Round #726 (Div.2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1537">Задачи</a></li> <li><a href="/contest/1537/submit">Отослать</a></li> <li><a href="/contest/1537/my">Мои посылки</a></li> <li><a href="/contest/1537/status">Статус</a></li> <li><a href="/contest/1537/hacks">Взломы</a></li> <li><a href="/contest/1537/room/1">Комната</a></li> <li><a href="/contest/1537/standings">Положение</a></li> <li><a href="/contest/1537/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2b0c1906f3950f89b82265bb5664f68eb5278901"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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">Это простая версия задачи. Единственное отличие — это ограничения на $$$n$$$ и $$$k$$$. Вы можете делать взломы, только если все версии задачи решены</span>.</p><p>У вас есть строка $$$s$$$, и вы можете выполнять над ней два типа операций: </p><ul> <li> Удалить последний символ строки. </li><li> Дублировать строку: $$$s:=s+s$$$, где $$$+$$$ обозначает конкатенацию. </li></ul><p>Вы можете использовать каждую операцию любое количество раз (возможно, ни одного).</p><p>Ваша задача — найти лексикографически наименьшую строку длины ровно $$$k$$$, которую можно получить, выполнив эти операции над строкой $$$s$$$.</p><p>Строка $$$a$$$ лексикографически меньше строки $$$b$$$ тогда и только тогда, когда выполняется одно из следующих условий:</p><ul> <li> $$$a$$$ является префиксом $$$b$$$, но $$$a\ne b$$$; </li><li> В первой позиции, где $$$a$$$ и $$$b$$$ отличаются, строка $$$a$$$ имеет букву, которая появляется раньше в алфавите, чем соответствующая буква в $$$b$$$. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$, $$$k$$$ ($$$1 \leq n, k \leq 5000$$$) — длину исходной строки $$$s$$$ и длину желаемой строки.</p><p>Вторая строка содержит строку $$$s$$$, состоящую из $$$n$$$ строчных английских букв.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите лексикографически наименьшую строку длины $$$k$$$, которая может быть получена путем выполнения операций над строкой $$$s$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 8 16 dbcadabc </pre></div><div class="output"><div class="title">Выходные данные</div><pre> dbcadabcdbcadabc </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 5 abcd </pre></div><div class="output"><div class="title">Выходные данные</div><pre> aaaaa </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте оптимально сделать одно дублирование: «<span class="tex-font-style-tt">dbcadabc</span>» $$$\to$$$ «<span class="tex-font-style-tt">dbcadabcdbcadabc</span>».</p><p>Во втором тесте оптимально удалить последние $$$3$$$ символа, затем продублировать строку $$$3$$$ раза, затем удалить последние $$$3$$$ символов, чтобы строка имела длину $$$k$$$.</p><p>«<span class="tex-font-style-tt">abcd</span>» $$$\to$$$ «<span class="tex-font-style-tt">abc</span>» $$$\to$$$ «<span class="tex-font-style-tt">ab</span>» $$$\to$$$ «<span class="tex-font-style-tt">a</span>» $$$\to$$$ «<span class="tex-font-style-tt">aa</span>» $$$\to$$$ «<span class="tex-font-style-tt">aaaa</span>» $$$\to$$$ «<span class="tex-font-style-tt">aaaa</span>» $$$\to$$$ «<span class="tex-font-style-tt">aaaa</span>» $$$\to$$$ «<span class="tex-font-style-tt">aaaa</span>» $$$\to$$$ «<span class="tex-font-style-tt">aaaa</span>».</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 11:29: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:'8124c635f9e07b67',t:'MTY5NjY2NzM0NC40NzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u043c\u0430\u0441\u0441\u0438\u0432\u044b, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u0438 \u0430\u0432\u0442\u043e\u043c\u0430\u0442\u044b", "\u0425\u044d\u0448\u0438, \u0445\u044d\u0448-\u0442\u0430\u0431\u043b\u0438\u0446\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u043e\u043a\u0438", "\u0441\u0442\u0440\u043e\u043a\u043e\u0432\u044b\u0435 \u0441\u0443\u0444\u0444. \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b", "\u0445\u044d\u0448\u0438", "*1600"]
1537E2
1537
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">Это сложная версия задачи. Единственное отличие — это ограничения на $$$n$$$ и $$$k$$$. Вы можете делать взломы, только если все версии задачи решены</span>.</p><p>У вас есть строка $$$s$$$, и вы можете выполнять над ней два типа операций: </p><ul> <li> Удалить последний символ строки. </li><li> Дублировать строку: $$$s:=s+s$$$, где $$$+$$$ обозначает конкатенацию. </li></ul><p>Вы можете использовать каждую операцию любое количество раз (возможно, ни одного).</p><p>Ваша задача — найти лексикографически наименьшую строку длины ровно $$$k$$$, которую можно получить, выполнив эти операции над строкой $$$s$$$.</p><p>Строка $$$a$$$ лексикографически меньше строки $$$b$$$ тогда и только тогда, когда выполняется одно из следующих условий:</p><ul> <li> $$$a$$$ является префиксом $$$b$$$, но $$$a\ne b$$$; </li><li> В первой позиции, где $$$a$$$ и $$$b$$$ отличаются, строка $$$a$$$ имеет букву, которая появляется раньше в алфавите, чем соответствующая буква в $$$b$$$. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$, $$$k$$$ ($$$1 \leq n, k \leq 5\cdot 10^5$$$) — длину исходной строки $$$s$$$ и длину желаемой строки.</p><p>Вторая строка содержит строку $$$s$$$, состоящую из $$$n$$$ строчных английских букв.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите лексикографически наименьшую строку длины $$$k$$$, которая может быть получена путем выполнения операций над строкой $$$s$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 8 16 dbcadabc </pre></div><div class="output"><div class="title">Выходные данные</div><pre> dbcadabcdbcadabc </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 5 abcd </pre></div><div class="output"><div class="title">Выходные данные</div><pre> aaaaa </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте оптимально сделать одно дублирование: «<span class="tex-font-style-tt">dbcadabc</span>» $$$\to$$$ «<span class="tex-font-style-tt">dbcadabcdbcadabc</span>».</p><p>Во втором тесте оптимально удалить последние $$$3$$$ символа, затем продублировать строку $$$3$$$ раза, затем удалить последние $$$3$$$ символов, чтобы строка имела длину $$$k$$$.</p><p>«<span class="tex-font-style-tt">abcd</span>» $$$\to$$$ «<span class="tex-font-style-tt">abc</span>» $$$\to$$$ «<span class="tex-font-style-tt">ab</span>» $$$\to$$$ «<span class="tex-font-style-tt">a</span>» $$$\to$$$ «<span class="tex-font-style-tt">aa</span>» $$$\to$$$ «<span class="tex-font-style-tt">aaaa</span>» $$$\to$$$ «<span class="tex-font-style-tt">aaaa</span>» $$$\to$$$ «<span class="tex-font-style-tt">aaaa</span>» $$$\to$$$ «<span class="tex-font-style-tt">aaaa</span>» $$$\to$$$ «<span class="tex-font-style-tt">aaaa</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="e22d415ac0cc51632b85008a15fdf336"/> <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="25f0f3ba0917aa9b09d150bb9b22b6ff3edf1109"/> <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='e22d415ac0cc51632b85008a15fdf336'>&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%2F1537%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='e22d415ac0cc51632b85008a15fdf336'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1537">Codeforces Round 726 (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='e22d415ac0cc51632b85008a15fdf336'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1537/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др."> строки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Суффиксные массивы, деревья и автоматы"> строковые суфф. структуры </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Хэши, хэш-таблицы"> хэши </span> </div> <div class="roundbox borderTopRound 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='e22d415ac0cc51632b85008a15fdf336'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1020037"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e22d415ac0cc51632b85008a15fdf336'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1020037"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91835" title="Codeforces Round #726 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13904" resourceName="Codeforces Round #726 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/91381" title="Codeforces Round #726 (Div.2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13907" resourceName="Codeforces Round #726 (Div.2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1537">Задачи</a></li> <li><a href="/contest/1537/submit">Отослать</a></li> <li><a href="/contest/1537/my">Мои посылки</a></li> <li><a href="/contest/1537/status">Статус</a></li> <li><a href="/contest/1537/hacks">Взломы</a></li> <li><a href="/contest/1537/room/1">Комната</a></li> <li><a href="/contest/1537/standings">Положение</a></li> <li><a href="/contest/1537/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_eb4fafff26b0f1a906540767aa541f40de07481a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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">Это сложная версия задачи. Единственное отличие — это ограничения на $$$n$$$ и $$$k$$$. Вы можете делать взломы, только если все версии задачи решены</span>.</p><p>У вас есть строка $$$s$$$, и вы можете выполнять над ней два типа операций: </p><ul> <li> Удалить последний символ строки. </li><li> Дублировать строку: $$$s:=s+s$$$, где $$$+$$$ обозначает конкатенацию. </li></ul><p>Вы можете использовать каждую операцию любое количество раз (возможно, ни одного).</p><p>Ваша задача — найти лексикографически наименьшую строку длины ровно $$$k$$$, которую можно получить, выполнив эти операции над строкой $$$s$$$.</p><p>Строка $$$a$$$ лексикографически меньше строки $$$b$$$ тогда и только тогда, когда выполняется одно из следующих условий:</p><ul> <li> $$$a$$$ является префиксом $$$b$$$, но $$$a\ne b$$$; </li><li> В первой позиции, где $$$a$$$ и $$$b$$$ отличаются, строка $$$a$$$ имеет букву, которая появляется раньше в алфавите, чем соответствующая буква в $$$b$$$. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$, $$$k$$$ ($$$1 \leq n, k \leq 5\cdot 10^5$$$) — длину исходной строки $$$s$$$ и длину желаемой строки.</p><p>Вторая строка содержит строку $$$s$$$, состоящую из $$$n$$$ строчных английских букв.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите лексикографически наименьшую строку длины $$$k$$$, которая может быть получена путем выполнения операций над строкой $$$s$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 8 16 dbcadabc </pre></div><div class="output"><div class="title">Выходные данные</div><pre> dbcadabcdbcadabc </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 5 abcd </pre></div><div class="output"><div class="title">Выходные данные</div><pre> aaaaa </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте оптимально сделать одно дублирование: «<span class="tex-font-style-tt">dbcadabc</span>» $$$\to$$$ «<span class="tex-font-style-tt">dbcadabcdbcadabc</span>».</p><p>Во втором тесте оптимально удалить последние $$$3$$$ символа, затем продублировать строку $$$3$$$ раза, затем удалить последние $$$3$$$ символов, чтобы строка имела длину $$$k$$$.</p><p>«<span class="tex-font-style-tt">abcd</span>» $$$\to$$$ «<span class="tex-font-style-tt">abc</span>» $$$\to$$$ «<span class="tex-font-style-tt">ab</span>» $$$\to$$$ «<span class="tex-font-style-tt">a</span>» $$$\to$$$ «<span class="tex-font-style-tt">aa</span>» $$$\to$$$ «<span class="tex-font-style-tt">aaaa</span>» $$$\to$$$ «<span class="tex-font-style-tt">aaaa</span>» $$$\to$$$ «<span class="tex-font-style-tt">aaaa</span>» $$$\to$$$ «<span class="tex-font-style-tt">aaaa</span>» $$$\to$$$ «<span class="tex-font-style-tt">aaaa</span>».</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 11:29: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:'8124c63e9b177903',t:'MTY5NjY2NzM0NS44MjYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\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"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u0442\u0440\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", "*2200"]
1537F
1537
F
ru
F. Исправляем фигуры
<div class="problem-statement"><div class="header"><div class="title">F. Исправляем фигуры</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть связный неориентированный граф, состоящий из $$$n$$$ вершин и $$$m$$$ ребер. У $$$i$$$-го узла есть начальное значение $$$v_i$$$ и целевое значение $$$t_i$$$.</p><p>За одну операцию можно выбрать любое ребро $$$(i, j)$$$ и добавить $$$k$$$ к $$$v_i$$$ и $$$v_j$$$, где $$$k$$$ может быть любым <span class="tex-font-style-bf">целым</span> числом. В частности, $$$k$$$ может быть отрицательным.</p><p>Ваша задача определить, можно ли, выполнив некоторое конечное число операций (возможно, ноль), добиться того, что каждого узла $$$i$$$, $$$v_i = t_i$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 1000$$$), количество наборов входных данных. Затем следуют наборы входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 2\cdot 10^5$$$, $$$n-1\leq m\leq \min(2\cdot 10^5, \frac{n(n-1)}{2})$$$) — количество вершин и ребер соответственно.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$v_1\ldots, v_n$$$ ($$$-10^9 \leq v_i \leq 10^9$$$) — начальные значения вершин.</p><p>Третья строка содержит $$$n$$$ целых чисел $$$t_1\ldots, t_n$$$ ($$$-10^9 \leq t_i \leq 10^9$$$) — целевые значения вершин.</p><p>Каждая из следующих $$$m$$$ строк содержит два целых числа $$$i$$$ и $$$j$$$, обозначающих ребро между вершинами $$$i$$$ и $$$j$$$ ($$$1 \leq i, j \leq n$$$, $$$i\ne j$$$).</p><p>Гарантируется, что граф связный и между одной парой вершин есть не более одного ребра.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$, а сумма $$$m$$$ по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого наборам входных данных, если возможно, чтобы значение в каждой вершине стало равно целевому после некоторого количества операций, выведите «<span class="tex-font-style-tt">YES</span>». В противном случае выведите «<span class="tex-font-style-tt">NO</span>».</p></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 5 1 2 -3 3 3 10 1 1 2 1 4 3 2 3 4 4 4 5 8 6 6 -3 1 15 4 1 2 1 4 3 2 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Вот визуализация первого тестового случая (оранжевые значения обозначают начальные значения, а синие — целевые): </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/54bbbac5584d746e714f114ae5ce18ee42fa99d8.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Один из возможных порядков действий для получения нужных значений для каждого узла следующий:</p><ul> <li> Операция $$$1$$$: Добавить $$$2$$$ к вершинами $$$2$$$ и $$$3$$$. </li><li> Операция $$$2$$$: Добавить $$$-2$$$ к вершинам $$$1$$$ и $$$4$$$. </li><li> Операция $$$3$$$: Добавить $$$6$$$ к вершинам $$$3$$$ и $$$4$$$. </li></ul><p>Теперь мы видим, что в общей сложности мы добавили $$$-2$$$ к вершине $$$1$$$, $$$2$$$ к вершине $$$2$$$, $$$8$$$ к вершине $$$3$$$ и $$$4$$$ к вершине $$$4$$$, что привело каждую вершину к нужному значению.</p><p>Для графа из второго набора входных данных получить нужные значения невозможно.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="1be9ca3c6a489d2f114c706561c4adcc"/> <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="25f0f3ba0917aa9b09d150bb9b22b6ff3edf1109"/> <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='1be9ca3c6a489d2f114c706561c4adcc'>&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%2F1537%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='1be9ca3c6a489d2f114c706561c4adcc'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1537">Codeforces Round 726 (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='1be9ca3c6a489d2f114c706561c4adcc'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1537/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='1be9ca3c6a489d2f114c706561c4adcc'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1020038"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1be9ca3c6a489d2f114c706561c4adcc'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1020038"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91835" title="Codeforces Round #726 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13904" resourceName="Codeforces Round #726 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/91381" title="Codeforces Round #726 (Div.2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13907" resourceName="Codeforces Round #726 (Div.2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1537">Задачи</a></li> <li><a href="/contest/1537/submit">Отослать</a></li> <li><a href="/contest/1537/my">Мои посылки</a></li> <li><a href="/contest/1537/status">Статус</a></li> <li><a href="/contest/1537/hacks">Взломы</a></li> <li><a href="/contest/1537/room/1">Комната</a></li> <li><a href="/contest/1537/standings">Положение</a></li> <li><a href="/contest/1537/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d226d848e7beb88d7e894a7c14f2548dbeab2c5a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ вершин и $$$m$$$ ребер. У $$$i$$$-го узла есть начальное значение $$$v_i$$$ и целевое значение $$$t_i$$$.</p><p>За одну операцию можно выбрать любое ребро $$$(i, j)$$$ и добавить $$$k$$$ к $$$v_i$$$ и $$$v_j$$$, где $$$k$$$ может быть любым <span class="tex-font-style-bf">целым</span> числом. В частности, $$$k$$$ может быть отрицательным.</p><p>Ваша задача определить, можно ли, выполнив некоторое конечное число операций (возможно, ноль), добиться того, что каждого узла $$$i$$$, $$$v_i = t_i$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 1000$$$), количество наборов входных данных. Затем следуют наборы входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$, $$$m$$$ ($$$2 \leq n \leq 2\cdot 10^5$$$, $$$n-1\leq m\leq \min(2\cdot 10^5, \frac{n(n-1)}{2})$$$) — количество вершин и ребер соответственно.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$v_1\ldots, v_n$$$ ($$$-10^9 \leq v_i \leq 10^9$$$) — начальные значения вершин.</p><p>Третья строка содержит $$$n$$$ целых чисел $$$t_1\ldots, t_n$$$ ($$$-10^9 \leq t_i \leq 10^9$$$) — целевые значения вершин.</p><p>Каждая из следующих $$$m$$$ строк содержит два целых числа $$$i$$$ и $$$j$$$, обозначающих ребро между вершинами $$$i$$$ и $$$j$$$ ($$$1 \leq i, j \leq n$$$, $$$i\ne j$$$).</p><p>Гарантируется, что граф связный и между одной парой вершин есть не более одного ребра.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$, а сумма $$$m$$$ по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого наборам входных данных, если возможно, чтобы значение в каждой вершине стало равно целевому после некоторого количества операций, выведите «<span class="tex-font-style-tt">YES</span>». В противном случае выведите «<span class="tex-font-style-tt">NO</span>».</p></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 5 1 2 -3 3 3 10 1 1 2 1 4 3 2 3 4 4 4 5 8 6 6 -3 1 15 4 1 2 1 4 3 2 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Вот визуализация первого тестового случая (оранжевые значения обозначают начальные значения, а синие — целевые): </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/54bbbac5584d746e714f114ae5ce18ee42fa99d8.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Один из возможных порядков действий для получения нужных значений для каждого узла следующий:</p><ul> <li> Операция $$$1$$$: Добавить $$$2$$$ к вершинами $$$2$$$ и $$$3$$$. </li><li> Операция $$$2$$$: Добавить $$$-2$$$ к вершинам $$$1$$$ и $$$4$$$. </li><li> Операция $$$3$$$: Добавить $$$6$$$ к вершинам $$$3$$$ и $$$4$$$. </li></ul><p>Теперь мы видим, что в общей сложности мы добавили $$$-2$$$ к вершине $$$1$$$, $$$2$$$ к вершине $$$2$$$, $$$8$$$ к вершине $$$3$$$ и $$$4$$$ к вершине $$$4$$$, что привело каждую вершину к нужному значению.</p><p>Для графа из второго набора входных данных получить нужные значения невозможно.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c6471dda9d3a',t:'MTY5NjY2NzM0Ny4zMTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u0438\u0441\u0442\u0435\u043c\u0430 \u043d\u0435\u043f\u0435\u0440\u0435\u0441\u0435\u043a\u0430\u044e\u0449\u0438\u0445\u0441\u044f \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u043d\u043c", "*2200"]
1538A
1538
A
ru
A. Каменная игра
<div class="problem-statement"><div class="header"><div class="title">A. Каменная игра</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Поликарп играет в новую компьютерную игру. В этой игре есть $$$n$$$ камней, выстроенных в ряд и пронумерованных слева направо. Камень с номером $$$i$$$ обладает целочисленной силой $$$a_i$$$. <span class="tex-font-style-bf">Силы всех камней различны</span>.</p><p>Каждый ход Поликарп может уничтожить либо камень с наименьшим номером, либо камень с наибольшим номером (другими словами, либо самый левый, либо самый правый) из еще не уничтоженных камней.</p><p>Сейчас Поликарп хочет получить два достижения. Он получит их, если уничтожит камень с <span class="tex-font-style-bf">наименьшей</span> силой и камень с <span class="tex-font-style-bf">наибольшей</span> силой. Помогите Поликарпу узнать, какое минимальное количество ходов он должен сделать, чтобы добиться своей цели.</p><p>Например, если $$$n = 5$$$ и $$$a = [1, 5, 4, 3, 2]$$$, то Поликарп мог делать следующие ходы: </p><ul> <li> Уничтожить самый левый камень. После этого хода $$$a = [5, 4, 3, 2]$$$. </li><li> Уничтожить самый правый камень. После этого хода $$$a = [5, 4, 3]$$$. </li><li> Уничтожить самый левый камень. После этого хода $$$a = [4, 3]$$$. Поликарп уничтожил камни с наибольшей и наименьшей силой, поэтому может заканчивать игру. </li></ul><p>Обратите внимание, что в примере выше можно закончить игру и за два шага. Например: </p><ul> <li> Уничтожить самый левый камень. После этого хода $$$a = [5, 4, 3, 2]$$$. </li><li> Уничтожить самый левый камень. После этого хода $$$a = [4, 3, 2]$$$. Поликарп уничтожил камни с наибольшей и наименьшей силой, поэтому может заканчивать игру. </li></ul><p>Найдите минимальное количество ходов, необходимое для уничтожения камней с наибольшей и наименьшей силой.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится целое число $$$t$$$ ($$$1 \le t \le 100$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора входных данных находится одно целое число $$$n$$$ ($$$2 \le n \le 100$$$) — количество камней.</p><p>Во второй строке находится $$$n$$$ целых различных чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — силы камней.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — минимальное количество ходов, необходимое для уничтожения камней с наибольшей и наименьшей силой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 5 1 5 4 3 2 8 2 1 3 4 5 6 8 7 8 4 2 3 1 8 6 7 5 4 3 4 2 1 4 2 3 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 4 5 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="340aba4b1836160905d3bdfb493af442"/> <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="761f01343f9ce123b9046d7c2a71822b83bc7291"/> <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='340aba4b1836160905d3bdfb493af442'>&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%2F1538%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='340aba4b1836160905d3bdfb493af442'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1538">Codeforces Round 725 (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='340aba4b1836160905d3bdfb493af442'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1538/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='340aba4b1836160905d3bdfb493af442'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1011921"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='340aba4b1836160905d3bdfb493af442'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1011921"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91602" title="Codeforces Round #725 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13853:13854" 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/91637" title="Codeforces Round #725 (Div. 3) Разбор" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13863:13864" 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/1538">Задачи</a></li> <li><a href="/contest/1538/submit">Отослать</a></li> <li><a href="/contest/1538/my">Мои посылки</a></li> <li><a href="/contest/1538/status">Статус</a></li> <li><a href="/contest/1538/hacks">Взломы</a></li> <li><a href="/contest/1538/standings">Положение</a></li> <li><a href="/contest/1538/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d09473e1faa871f7bdf5002c17809f177d48550a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Каменная игра</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Поликарп играет в новую компьютерную игру. В этой игре есть $$$n$$$ камней, выстроенных в ряд и пронумерованных слева направо. Камень с номером $$$i$$$ обладает целочисленной силой $$$a_i$$$. <span class="tex-font-style-bf">Силы всех камней различны</span>.</p><p>Каждый ход Поликарп может уничтожить либо камень с наименьшим номером, либо камень с наибольшим номером (другими словами, либо самый левый, либо самый правый) из еще не уничтоженных камней.</p><p>Сейчас Поликарп хочет получить два достижения. Он получит их, если уничтожит камень с <span class="tex-font-style-bf">наименьшей</span> силой и камень с <span class="tex-font-style-bf">наибольшей</span> силой. Помогите Поликарпу узнать, какое минимальное количество ходов он должен сделать, чтобы добиться своей цели.</p><p>Например, если $$$n = 5$$$ и $$$a = [1, 5, 4, 3, 2]$$$, то Поликарп мог делать следующие ходы: </p><ul> <li> Уничтожить самый левый камень. После этого хода $$$a = [5, 4, 3, 2]$$$. </li><li> Уничтожить самый правый камень. После этого хода $$$a = [5, 4, 3]$$$. </li><li> Уничтожить самый левый камень. После этого хода $$$a = [4, 3]$$$. Поликарп уничтожил камни с наибольшей и наименьшей силой, поэтому может заканчивать игру. </li></ul><p>Обратите внимание, что в примере выше можно закончить игру и за два шага. Например: </p><ul> <li> Уничтожить самый левый камень. После этого хода $$$a = [5, 4, 3, 2]$$$. </li><li> Уничтожить самый левый камень. После этого хода $$$a = [4, 3, 2]$$$. Поликарп уничтожил камни с наибольшей и наименьшей силой, поэтому может заканчивать игру. </li></ul><p>Найдите минимальное количество ходов, необходимое для уничтожения камней с наибольшей и наименьшей силой.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится целое число $$$t$$$ ($$$1 \le t \le 100$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора входных данных находится одно целое число $$$n$$$ ($$$2 \le n \le 100$$$) — количество камней.</p><p>Во второй строке находится $$$n$$$ целых различных чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — силы камней.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — минимальное количество ходов, необходимое для уничтожения камней с наибольшей и наименьшей силой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 5 1 5 4 3 2 8 2 1 3 4 5 6 8 7 8 4 2 3 1 8 6 7 5 4 3 4 2 1 4 2 3 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 4 5 3 2 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c6507ae716af',t:'MTY5NjY2NzM0OC42NzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*800"]
1538B
1538
B
ru
B. Друзья и конфеты
<div class="problem-statement"><div class="header"><div class="title">B. Друзья и конфеты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Поликарпа есть $$$n$$$ друзей, у $$$i$$$-го из которых есть $$$a_i$$$ конфет. Друзьям Поликарпа не нравится, когда у них различается количество конфет. Иными словами, они хотят, чтобы все $$$a_i$$$ были равны. Чтобы добиться этого, Поликарп делает следующее <span class="tex-font-style-bf">ровно один раз</span>: </p><ul> <li> Поликарп выбирает $$$k$$$ ($$$0 \le k \le n$$$) произвольных друзей (пусть он выбрал друзей с номерами $$$i_1, i_2, \ldots, i_k$$$); </li><li> Поликарп перераспределяет их конфеты среди всех $$$n$$$ друзей, всего таких конфет $$$a_{i_1} + a_{i_2} + \ldots + a_{i_k}$$$. При перераспределении для каждой конфеты из $$$a_{i_1} + a_{i_2} + \ldots + a_{i_k}$$$ он выбирает нового владельца (любого из $$$n$$$ друзей, конфета может вновь достаться старому владельцу). </li></ul><p>Заметьте, что число $$$k$$$ заранее не фиксировано и может быть произвольным. Ваша задача — найти минимальное возможное значение $$$k$$$.</p><p>Например, если $$$n=4$$$ и $$$a=[4, 5, 2, 5]$$$, тогда Поликарп мог сделать следующее: </p><ul> <li> Поликарп выбирает $$$k=2$$$ друзей с номерами $$$i=[2, 4]$$$ и перераспределяет $$$a_2 + a_4 = 10$$$ конфет так, что в итоге $$$a=[4, 4, 4, 4]$$$ (две конфеты достаются человеку под номером $$$3$$$). </li></ul><p>Заметьте, что в данном примере Поликарп не может выбрать $$$k=1$$$ друга так, чтобы можно было перераспределить конфеты так, что в итоге все $$$a_i$$$ равны между собой.</p><p>Для данных $$$n$$$ и $$$a$$$ определите <span class="tex-font-style-bf">минимальное</span> значение $$$k$$$. При этом значении $$$k$$$ Поликарп должен иметь возможность выбрать $$$k$$$ друзей и перераспределить их конфеты так, что у всех в итоге будет одинаковое количество конфет.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора входных данных содержится одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$).</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^4$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите: </p><ul> <li> минимальное значение $$$k$$$ при котором Поликарп может выбрать ровно $$$k$$$ друзей так, чтобы можно было перераспределить конфеты искомым образом; </li><li> «<span class="tex-font-style-tt">-1</span>», если такого значения $$$k$$$ не существует. </li></ul></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 4 4 5 2 5 2 0 4 5 10 8 5 1 4 1 10000 7 1 1 1 1 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 -1 0 0 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="3856f394529d8dee782d16d36256372b"/> <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="761f01343f9ce123b9046d7c2a71822b83bc7291"/> <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='3856f394529d8dee782d16d36256372b'>&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%2F1538%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='3856f394529d8dee782d16d36256372b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1538">Codeforces Round 725 (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='3856f394529d8dee782d16d36256372b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1538/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *800 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3856f394529d8dee782d16d36256372b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1011922"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3856f394529d8dee782d16d36256372b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1011922"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91602" title="Codeforces Round #725 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13853:13854" 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/91637" title="Codeforces Round #725 (Div. 3) Разбор" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13863:13864" 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/1538">Задачи</a></li> <li><a href="/contest/1538/submit">Отослать</a></li> <li><a href="/contest/1538/my">Мои посылки</a></li> <li><a href="/contest/1538/status">Статус</a></li> <li><a href="/contest/1538/hacks">Взломы</a></li> <li><a href="/contest/1538/standings">Положение</a></li> <li><a href="/contest/1538/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_19a33dbf07e06a6fc58cd3f0d09fbdc999640944"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Друзья и конфеты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Поликарпа есть $$$n$$$ друзей, у $$$i$$$-го из которых есть $$$a_i$$$ конфет. Друзьям Поликарпа не нравится, когда у них различается количество конфет. Иными словами, они хотят, чтобы все $$$a_i$$$ были равны. Чтобы добиться этого, Поликарп делает следующее <span class="tex-font-style-bf">ровно один раз</span>: </p><ul> <li> Поликарп выбирает $$$k$$$ ($$$0 \le k \le n$$$) произвольных друзей (пусть он выбрал друзей с номерами $$$i_1, i_2, \ldots, i_k$$$); </li><li> Поликарп перераспределяет их конфеты среди всех $$$n$$$ друзей, всего таких конфет $$$a_{i_1} + a_{i_2} + \ldots + a_{i_k}$$$. При перераспределении для каждой конфеты из $$$a_{i_1} + a_{i_2} + \ldots + a_{i_k}$$$ он выбирает нового владельца (любого из $$$n$$$ друзей, конфета может вновь достаться старому владельцу). </li></ul><p>Заметьте, что число $$$k$$$ заранее не фиксировано и может быть произвольным. Ваша задача — найти минимальное возможное значение $$$k$$$.</p><p>Например, если $$$n=4$$$ и $$$a=[4, 5, 2, 5]$$$, тогда Поликарп мог сделать следующее: </p><ul> <li> Поликарп выбирает $$$k=2$$$ друзей с номерами $$$i=[2, 4]$$$ и перераспределяет $$$a_2 + a_4 = 10$$$ конфет так, что в итоге $$$a=[4, 4, 4, 4]$$$ (две конфеты достаются человеку под номером $$$3$$$). </li></ul><p>Заметьте, что в данном примере Поликарп не может выбрать $$$k=1$$$ друга так, чтобы можно было перераспределить конфеты так, что в итоге все $$$a_i$$$ равны между собой.</p><p>Для данных $$$n$$$ и $$$a$$$ определите <span class="tex-font-style-bf">минимальное</span> значение $$$k$$$. При этом значении $$$k$$$ Поликарп должен иметь возможность выбрать $$$k$$$ друзей и перераспределить их конфеты так, что у всех в итоге будет одинаковое количество конфет.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора входных данных содержится одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$).</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^4$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите: </p><ul> <li> минимальное значение $$$k$$$ при котором Поликарп может выбрать ровно $$$k$$$ друзей так, чтобы можно было перераспределить конфеты искомым образом; </li><li> «<span class="tex-font-style-tt">-1</span>», если такого значения $$$k$$$ не существует. </li></ul></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 4 4 5 2 5 2 0 4 5 10 8 5 1 4 1 10000 7 1 1 1 1 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 -1 0 0 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c6590fa09d37',t:'MTY5NjY2NzM1MC4wNDMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*800"]
1538C
1538
C
ru
C. Количество пар
<div class="problem-statement"><div class="header"><div class="title">C. Количество пар</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задан массив $$$a$$$, состоящий из $$$n$$$ целых чисел. Найдите количество пар индексов $$$(i, j)$$$ ($$$1 \le i &lt; j \le n$$$), для которых сумма $$$a_i + a_j$$$ больше или равна $$$l$$$ и меньше или равна $$$r$$$ (то есть $$$l \le a_i + a_j \le r$$$).</p><p>Например, если $$$n = 3$$$, $$$a = [5, 1, 2]$$$, $$$l = 4$$$ и $$$r = 7$$$, то подходят две пары: </p><ul> <li> $$$i=1$$$ и $$$j=2$$$ ($$$4 \le 5 + 1 \le 7$$$); </li><li> $$$i=1$$$ и $$$j=3$$$ ($$$4 \le 5 + 2 \le 7$$$). </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора входных данных находятся три целых числа $$$n, l, r$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le l \le r \le 10^9$$$) — количество чисел в массиве и ограничения на сумму в паре.</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). </p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — количество пар индексов $$$(i, j)$$$ ($$$i &lt; j$$$), для которых $$$l \le a_i + a_j \le r$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 4 7 5 1 2 5 5 8 5 1 2 4 3 4 100 1000 1 1 1 1 5 9 13 2 5 5 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 7 0 1 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="03219d2df36c280ab71068ba00552b3a"/> <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="761f01343f9ce123b9046d7c2a71822b83bc7291"/> <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='03219d2df36c280ab71068ba00552b3a'>&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%2F1538%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='03219d2df36c280ab71068ba00552b3a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1538">Codeforces Round 725 (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='03219d2df36c280ab71068ba00552b3a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1538/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *1300 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='03219d2df36c280ab71068ba00552b3a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1011923"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='03219d2df36c280ab71068ba00552b3a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1011923"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91602" title="Codeforces Round #725 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13853:13854" 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/91637" title="Codeforces Round #725 (Div. 3) Разбор" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13863:13864" 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/1538">Задачи</a></li> <li><a href="/contest/1538/submit">Отослать</a></li> <li><a href="/contest/1538/my">Мои посылки</a></li> <li><a href="/contest/1538/status">Статус</a></li> <li><a href="/contest/1538/hacks">Взломы</a></li> <li><a href="/contest/1538/standings">Положение</a></li> <li><a href="/contest/1538/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_6c59b418bf27c994845b2e37b926b423ea8f2f85"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Количество пар</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задан массив $$$a$$$, состоящий из $$$n$$$ целых чисел. Найдите количество пар индексов $$$(i, j)$$$ ($$$1 \le i &lt; j \le n$$$), для которых сумма $$$a_i + a_j$$$ больше или равна $$$l$$$ и меньше или равна $$$r$$$ (то есть $$$l \le a_i + a_j \le r$$$).</p><p>Например, если $$$n = 3$$$, $$$a = [5, 1, 2]$$$, $$$l = 4$$$ и $$$r = 7$$$, то подходят две пары: </p><ul> <li> $$$i=1$$$ и $$$j=2$$$ ($$$4 \le 5 + 1 \le 7$$$); </li><li> $$$i=1$$$ и $$$j=3$$$ ($$$4 \le 5 + 2 \le 7$$$). </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора входных данных находятся три целых числа $$$n, l, r$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le l \le r \le 10^9$$$) — количество чисел в массиве и ограничения на сумму в паре.</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). </p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — количество пар индексов $$$(i, j)$$$ ($$$i &lt; j$$$), для которых $$$l \le a_i + a_j \le r$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 4 7 5 1 2 5 5 8 5 1 2 4 3 4 100 1000 1 1 1 1 5 9 13 2 5 5 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 7 0 1 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29:11</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c66169359da2',t:'MTY5NjY2NzM1MS40NDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\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", "*1300"]
1538D
1538
D
ru
D. Еще одна задача про деление чисел
<div class="problem-statement"><div class="header"><div class="title">D. Еще одна задача про деление чисел</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны два целых числа $$$a$$$ и $$$b$$$. За один ход вы можете выполнить одно из следующих действий: </p><ul> <li> Взять целое число $$$c$$$ ($$$c &gt; 1$$$, <span class="tex-font-style-bf">$$$a$$$ делится на $$$c$$$</span>) и заменить $$$a$$$ на $$$\frac{a}{c}$$$; </li><li> Взять целое число $$$c$$$ ($$$c &gt; 1$$$, <span class="tex-font-style-bf">$$$b$$$ делится на $$$c$$$</span>) и заменить $$$b$$$ на $$$\frac{b}{c}$$$. </li></ul><p>Ваша цель сделать $$$a$$$ равным $$$b$$$, используя $$$k$$$ этих операций.</p><p>Например, числа $$$a=36$$$ и $$$b=48$$$ можно сделать равными за $$$4$$$ хода: </p><ul> <li> $$$c=6$$$, делим $$$b$$$ на $$$c$$$ $$$\Rightarrow$$$ $$$a=36$$$, $$$b=8$$$; </li><li> $$$c=2$$$, делим $$$a$$$ на $$$c$$$ $$$\Rightarrow$$$ $$$a=18$$$, $$$b=8$$$; </li><li> $$$c=9$$$, делим $$$a$$$ на $$$c$$$ $$$\Rightarrow$$$ $$$a=2$$$, $$$b=8$$$; </li><li> $$$c=4$$$, делим $$$b$$$ на $$$c$$$ $$$\Rightarrow$$$ $$$a=2$$$, $$$b=2$$$. </li></ul><p>Для заданных чисел $$$a$$$ и $$$b$$$ определите, можно ли сделать их равными <span class="tex-font-style-bf">ровно</span> за $$$k$$$ ходов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор входных данных характеризуется тремя целыми числами $$$a$$$, $$$b$$$ и $$$k$$$ ($$$1 \le a, b, k \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите: </p><ul> <li> «<span class="tex-font-style-tt">Yes</span>», если можно ли сделать числа $$$a$$$ и $$$b$$$ равными <span class="tex-font-style-bf">ровно</span> за $$$k$$$ ходов; </li><li> «<span class="tex-font-style-tt">No</span>», иначе. </li></ul><p>Строки «<span class="tex-font-style-tt">Yes</span>» и «<span class="tex-font-style-tt">No</span>» можно выводить в произвольном регистре.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 8 36 48 2 36 48 3 36 48 4 2 8 1 2 8 2 1000000000 1000000000 1000000000 1 2 1 2 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES YES YES YES NO YES NO </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="3b8b4f9ea8baf8a8ed975865d493351f"/> <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="761f01343f9ce123b9046d7c2a71822b83bc7291"/> <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='3b8b4f9ea8baf8a8ed975865d493351f'>&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%2F1538%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='3b8b4f9ea8baf8a8ed975865d493351f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1538">Codeforces Round 725 (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='3b8b4f9ea8baf8a8ed975865d493351f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1538/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='3b8b4f9ea8baf8a8ed975865d493351f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1011924"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3b8b4f9ea8baf8a8ed975865d493351f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1011924"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91602" title="Codeforces Round #725 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13853:13854" 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/91637" title="Codeforces Round #725 (Div. 3) Разбор" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13863:13864" 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/1538">Задачи</a></li> <li><a href="/contest/1538/submit">Отослать</a></li> <li><a href="/contest/1538/my">Мои посылки</a></li> <li><a href="/contest/1538/status">Статус</a></li> <li><a href="/contest/1538/hacks">Взломы</a></li> <li><a href="/contest/1538/standings">Положение</a></li> <li><a href="/contest/1538/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_89d72b4d26dc04c715fffd8b7985a297e242063d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Еще одна задача про деление чисел</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны два целых числа $$$a$$$ и $$$b$$$. За один ход вы можете выполнить одно из следующих действий: </p><ul> <li> Взять целое число $$$c$$$ ($$$c &gt; 1$$$, <span class="tex-font-style-bf">$$$a$$$ делится на $$$c$$$</span>) и заменить $$$a$$$ на $$$\frac{a}{c}$$$; </li><li> Взять целое число $$$c$$$ ($$$c &gt; 1$$$, <span class="tex-font-style-bf">$$$b$$$ делится на $$$c$$$</span>) и заменить $$$b$$$ на $$$\frac{b}{c}$$$. </li></ul><p>Ваша цель сделать $$$a$$$ равным $$$b$$$, используя $$$k$$$ этих операций.</p><p>Например, числа $$$a=36$$$ и $$$b=48$$$ можно сделать равными за $$$4$$$ хода: </p><ul> <li> $$$c=6$$$, делим $$$b$$$ на $$$c$$$ $$$\Rightarrow$$$ $$$a=36$$$, $$$b=8$$$; </li><li> $$$c=2$$$, делим $$$a$$$ на $$$c$$$ $$$\Rightarrow$$$ $$$a=18$$$, $$$b=8$$$; </li><li> $$$c=9$$$, делим $$$a$$$ на $$$c$$$ $$$\Rightarrow$$$ $$$a=2$$$, $$$b=8$$$; </li><li> $$$c=4$$$, делим $$$b$$$ на $$$c$$$ $$$\Rightarrow$$$ $$$a=2$$$, $$$b=2$$$. </li></ul><p>Для заданных чисел $$$a$$$ и $$$b$$$ определите, можно ли сделать их равными <span class="tex-font-style-bf">ровно</span> за $$$k$$$ ходов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор входных данных характеризуется тремя целыми числами $$$a$$$, $$$b$$$ и $$$k$$$ ($$$1 \le a, b, k \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите: </p><ul> <li> «<span class="tex-font-style-tt">Yes</span>», если можно ли сделать числа $$$a$$$ и $$$b$$$ равными <span class="tex-font-style-bf">ровно</span> за $$$k$$$ ходов; </li><li> «<span class="tex-font-style-tt">No</span>», иначе. </li></ul><p>Строки «<span class="tex-font-style-tt">Yes</span>» и «<span class="tex-font-style-tt">No</span>» можно выводить в произвольном регистре.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 8 36 48 2 36 48 3 36 48 4 2 8 1 2 8 2 1000000000 1000000000 1000000000 1 2 1 2 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES YES YES YES NO YES NO </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c66a4d8715fe',t:'MTY5NjY2NzM1Mi44ODAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1700"]
1538E
1538
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><ol> <li> «<span class="tex-font-style-tt">x := s</span>» — назначить переменной с именем <span class="tex-font-style-tt">x</span> значение <span class="tex-font-style-tt">s</span> (где <span class="tex-font-style-tt">s</span> - строка). Например, команда <span class="tex-font-style-tt">var := hello</span> присваивает переменной с именем <span class="tex-font-style-tt">var</span> значение <span class="tex-font-style-tt">hello</span>. Обратите внимание, что <span class="tex-font-style-tt">s</span> - это значение строки, а не имя переменной. Между названием переменной, оператором <span class="tex-font-style-tt">:=</span> и строкой находится ровно по одному пробелу. </li><li> «<span class="tex-font-style-tt">x = a + b</span>» — назначить переменной с именем <span class="tex-font-style-tt">x</span> конкатенацию двух переменных <span class="tex-font-style-tt">a</span> и <span class="tex-font-style-tt">b</span>. Например, если программа состоит из трех команд <span class="tex-font-style-tt">a := hello</span>, <span class="tex-font-style-tt">b := world</span>, <span class="tex-font-style-tt">c = a + b</span>, то переменная <span class="tex-font-style-tt">c</span> будет содержать строку <span class="tex-font-style-tt">helloworld</span>. Гарантируется, что программа корректна и переменные <span class="tex-font-style-tt">a</span> и <span class="tex-font-style-tt">b</span> были определены ранее. Между названиями переменных и операторами <span class="tex-font-style-tt">=</span> и <span class="tex-font-style-tt">+</span> находится ровно по одному пробелу. </li></ol><p>Все имена переменных и строки состоят только из строчных букв английского алфавита и состоят не больше, чем из $$$5$$$ символов.</p><p>Результатом работы программы является количество вхождений строки <span class="tex-font-style-tt">haha</span> в строке, которая была записана в переменную в последней команде.</p><p>Поликарп очень устал, изобретая этот язык. Он просит вас реализовать его. Ваша задача состоит в том, чтобы — для заданных программных операторов вычислить количество вхождений строки <span class="tex-font-style-tt">haha</span> в последней назначенной переменной.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится целое число $$$t$$$ ($$$1 \le t \le 10^3$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора входных данных находятся одно целое число $$$n$$$ — ($$$1 \le n \le 50$$$) — количество команд в программе. Все имена переменных и строки гарантированно состоят только из строчных букв английского алфавита и состоят не больше, чем из $$$5$$$ символов.</p><p>Далее следуют $$$n$$$ строк описывающих команды в формате из условия выше. Гарантируется, что программа корректна.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите количество вхождений подстроки <span class="tex-font-style-tt">haha</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 6 a := h b := aha c = a + b c = c + c e = c + c d = a + c 15 x := haha x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x 1 haha := hah 5 haahh := aaaha ahhhh = haahh + haahh haahh = haahh + haahh ahhhh = ahhhh + haahh ahhaa = haahh + ahhhh </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 32767 0 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных результат — значение переменной <span class="tex-font-style-tt">d=hhahahaha</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="0e8d311f7eb62bd9c2a445310009868b"/> <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="761f01343f9ce123b9046d7c2a71822b83bc7291"/> <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='0e8d311f7eb62bd9c2a445310009868b'>&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%2F1538%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='0e8d311f7eb62bd9c2a445310009868b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1538">Codeforces Round 725 (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='0e8d311f7eb62bd9c2a445310009868b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1538/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='0e8d311f7eb62bd9c2a445310009868b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1011925"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0e8d311f7eb62bd9c2a445310009868b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1011925"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91602" title="Codeforces Round #725 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13853:13854" 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/91637" title="Codeforces Round #725 (Div. 3) Разбор" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13863:13864" 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/1538">Задачи</a></li> <li><a href="/contest/1538/submit">Отослать</a></li> <li><a href="/contest/1538/my">Мои посылки</a></li> <li><a href="/contest/1538/status">Статус</a></li> <li><a href="/contest/1538/hacks">Взломы</a></li> <li><a href="/contest/1538/standings">Положение</a></li> <li><a href="/contest/1538/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8e27fc45849cf9cd96de1f0df67fbcca55d6b4fc"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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><ol> <li> «<span class="tex-font-style-tt">x := s</span>» — назначить переменной с именем <span class="tex-font-style-tt">x</span> значение <span class="tex-font-style-tt">s</span> (где <span class="tex-font-style-tt">s</span> - строка). Например, команда <span class="tex-font-style-tt">var := hello</span> присваивает переменной с именем <span class="tex-font-style-tt">var</span> значение <span class="tex-font-style-tt">hello</span>. Обратите внимание, что <span class="tex-font-style-tt">s</span> - это значение строки, а не имя переменной. Между названием переменной, оператором <span class="tex-font-style-tt">:=</span> и строкой находится ровно по одному пробелу. </li><li> «<span class="tex-font-style-tt">x = a + b</span>» — назначить переменной с именем <span class="tex-font-style-tt">x</span> конкатенацию двух переменных <span class="tex-font-style-tt">a</span> и <span class="tex-font-style-tt">b</span>. Например, если программа состоит из трех команд <span class="tex-font-style-tt">a := hello</span>, <span class="tex-font-style-tt">b := world</span>, <span class="tex-font-style-tt">c = a + b</span>, то переменная <span class="tex-font-style-tt">c</span> будет содержать строку <span class="tex-font-style-tt">helloworld</span>. Гарантируется, что программа корректна и переменные <span class="tex-font-style-tt">a</span> и <span class="tex-font-style-tt">b</span> были определены ранее. Между названиями переменных и операторами <span class="tex-font-style-tt">=</span> и <span class="tex-font-style-tt">+</span> находится ровно по одному пробелу. </li></ol><p>Все имена переменных и строки состоят только из строчных букв английского алфавита и состоят не больше, чем из $$$5$$$ символов.</p><p>Результатом работы программы является количество вхождений строки <span class="tex-font-style-tt">haha</span> в строке, которая была записана в переменную в последней команде.</p><p>Поликарп очень устал, изобретая этот язык. Он просит вас реализовать его. Ваша задача состоит в том, чтобы — для заданных программных операторов вычислить количество вхождений строки <span class="tex-font-style-tt">haha</span> в последней назначенной переменной.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится целое число $$$t$$$ ($$$1 \le t \le 10^3$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора входных данных находятся одно целое число $$$n$$$ — ($$$1 \le n \le 50$$$) — количество команд в программе. Все имена переменных и строки гарантированно состоят только из строчных букв английского алфавита и состоят не больше, чем из $$$5$$$ символов.</p><p>Далее следуют $$$n$$$ строк описывающих команды в формате из условия выше. Гарантируется, что программа корректна.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите количество вхождений подстроки <span class="tex-font-style-tt">haha</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 6 a := h b := aha c = a + b c = c + c e = c + c d = a + c 15 x := haha x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x x = x + x 1 haha := hah 5 haahh := aaaha ahhhh = haahh + haahh haahh = haahh + haahh ahhhh = ahhhh + haahh ahhaa = haahh + ahhhh </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 32767 0 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных результат — значение переменной <span class="tex-font-style-tt">d=hhahahaha</span>.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c6733ab115f6',t:'MTY5NjY2NzM1NC4xOTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u043c\u0430\u0442\u0440\u0438\u0446, \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u044c, \u043f\u0440\u0430\u0432\u0438\u043b\u043e \u041a\u0440\u0430\u043c\u0435\u0440\u0430, \u0441\u0438\u0441\u0442\u0435\u043c\u044b \u043b\u0438\u043d\u0435\u0439\u043d\u044b\u0445 \u0443\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u0439", "\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.", "\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"]
["\u043c\u0430\u0442\u0440\u0438\u0446\u044b", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u043e\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "\u0445\u044d\u0448\u0438", "*2100"]
1538F
1538
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>Вам заданы два целых числа $$$l$$$ и $$$r$$$, где $$$l &lt; r$$$. Будем прибавлять $$$1$$$ к $$$l$$$ до тех пор, пока результат не окажется равным $$$r$$$. Таким образом, будет сделано ровно $$$r-l$$$ прибавлений единицы. Для каждого такого прибавления посмотрим на количество цифр, которые будут изменены при этом прибавлении. Например: </p><ul> <li> если $$$l=909$$$, то прибавление единицы приведёт к результату $$$910$$$ и будут изменены $$$2$$$ цифры; </li><li> если к $$$l=9$$$ прибавить единицу, то результат будет равен $$$10$$$ и будут изменены тоже $$$2$$$ цифры; </li><li> если к $$$l=489999$$$ прибавить единицу, то результат будет равен $$$490000$$$ и будут изменены $$$5$$$ цифр. </li></ul><p>Изменённые цифры всегда образуют некоторый суффикс десятичной записи результата.</p><p>Выведите суммарное количество изменённых цифр, если требуется из $$$l$$$ получить $$$r$$$, прибавляя каждый раз $$$1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый дабор входных данных характеризуется двумя целыми числами $$$l$$$ и $$$r$$$ ($$$1 \le l &lt; r \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных вычислите суммарное количество изменённых цифр, если требуется из $$$l$$$ получить $$$r$$$, прибавляя каждый раз единицу.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 1 9 9 10 10 20 1 1000000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 2 11 1111111110 </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="65c7276823394229372108bf522262ab"/> <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="761f01343f9ce123b9046d7c2a71822b83bc7291"/> <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='65c7276823394229372108bf522262ab'>&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%2F1538%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='65c7276823394229372108bf522262ab'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1538">Codeforces Round 725 (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='65c7276823394229372108bf522262ab'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1538/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='65c7276823394229372108bf522262ab'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1011926"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='65c7276823394229372108bf522262ab'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1011926"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91602" title="Codeforces Round #725 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13853:13854" 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/91637" title="Codeforces Round #725 (Div. 3) Разбор" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13863:13864" 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/1538">Задачи</a></li> <li><a href="/contest/1538/submit">Отослать</a></li> <li><a href="/contest/1538/my">Мои посылки</a></li> <li><a href="/contest/1538/status">Статус</a></li> <li><a href="/contest/1538/hacks">Взломы</a></li> <li><a href="/contest/1538/standings">Положение</a></li> <li><a href="/contest/1538/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_db3db5724d34dd30ee4aaa46c8bc5ae101495d49"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Вам заданы два целых числа $$$l$$$ и $$$r$$$, где $$$l &lt; r$$$. Будем прибавлять $$$1$$$ к $$$l$$$ до тех пор, пока результат не окажется равным $$$r$$$. Таким образом, будет сделано ровно $$$r-l$$$ прибавлений единицы. Для каждого такого прибавления посмотрим на количество цифр, которые будут изменены при этом прибавлении. Например: </p><ul> <li> если $$$l=909$$$, то прибавление единицы приведёт к результату $$$910$$$ и будут изменены $$$2$$$ цифры; </li><li> если к $$$l=9$$$ прибавить единицу, то результат будет равен $$$10$$$ и будут изменены тоже $$$2$$$ цифры; </li><li> если к $$$l=489999$$$ прибавить единицу, то результат будет равен $$$490000$$$ и будут изменены $$$5$$$ цифр. </li></ul><p>Изменённые цифры всегда образуют некоторый суффикс десятичной записи результата.</p><p>Выведите суммарное количество изменённых цифр, если требуется из $$$l$$$ получить $$$r$$$, прибавляя каждый раз $$$1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый дабор входных данных характеризуется двумя целыми числами $$$l$$$ и $$$r$$$ ($$$1 \le l &lt; r \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных вычислите суммарное количество изменённых цифр, если требуется из $$$l$$$ получить $$$r$$$, прибавляя каждый раз единицу.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 1 9 9 10 10 20 1 1000000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 2 11 1111111110 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c67b5e2d9d45',t:'MTY5NjY2NzM1NS41NDYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\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\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u043f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1500"]
1538G
1538
G
ru
G. Подарочный набор
<div class="problem-statement"><div class="header"><div class="title">G. Подарочный набор</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Поликарпа есть $$$x$$$ красных и $$$y$$$ синих конфет. Из них он хочет составить подарочные наборы. Каждый подарочный набор будет содержать либо $$$a$$$ красных конфет и $$$b$$$ синих конфет, либо наоборот — $$$a$$$ синих конфет и $$$b$$$ красных конфет.</p><p>Помогите Поликарпу понять, какое наибольшее число подарочных наборов он может составить. </p><p>Например, если $$$x = 10$$$, $$$y = 12$$$, $$$a = 5$$$ и $$$b = 2$$$, то он может составить три подарочных набора: </p><ul> <li> В первом наборе будет $$$5$$$ красных конфет и $$$2$$$ синие; </li><li> Во втором наборе будет $$$5$$$ синих конфет и $$$2$$$ красные; </li><li> В третьем наборе будет $$$5$$$ синих конфет и $$$2$$$ красные. </li></ul><p>У Поликарпа останется одна красная конфета, используя которую, он не сможет собрать еще один подарочный набор.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор входных данных состоит из одной строки в которой находятся четыре целых числа $$$x$$$, $$$y$$$, $$$a$$$ и $$$b$$$ ($$$1 \le x, y, a, b \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно число — максимальное количество подарочных наборов, которое может собрать Поликарп.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 9 10 12 2 5 1 1 2 2 52 311 13 27 1000000000 1000000000 1 1 1000000000 1 1 1000000000 1 1000000000 1000000000 1 1 2 1 1 7 8 1 2 4 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 0 4 1000000000 1 1 1 5 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="59580188c82957afaa22da2c0ffb356d"/> <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="761f01343f9ce123b9046d7c2a71822b83bc7291"/> <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='59580188c82957afaa22da2c0ffb356d'>&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%2F1538%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='59580188c82957afaa22da2c0ffb356d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1538">Codeforces Round 725 (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='59580188c82957afaa22da2c0ffb356d'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1538/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Тернарный поиск"> тернарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *2100 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='59580188c82957afaa22da2c0ffb356d'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1011927"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='59580188c82957afaa22da2c0ffb356d'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1011927"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91602" title="Codeforces Round #725 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13853:13854" 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/91637" title="Codeforces Round #725 (Div. 3) Разбор" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13863:13864" 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/1538">Задачи</a></li> <li><a href="/contest/1538/submit">Отослать</a></li> <li><a href="/contest/1538/my">Мои посылки</a></li> <li><a href="/contest/1538/status">Статус</a></li> <li><a href="/contest/1538/hacks">Взломы</a></li> <li><a href="/contest/1538/standings">Положение</a></li> <li><a href="/contest/1538/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f3baaea28eee810cec74f67e0c157086af2c5c4f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>У Поликарпа есть $$$x$$$ красных и $$$y$$$ синих конфет. Из них он хочет составить подарочные наборы. Каждый подарочный набор будет содержать либо $$$a$$$ красных конфет и $$$b$$$ синих конфет, либо наоборот — $$$a$$$ синих конфет и $$$b$$$ красных конфет.</p><p>Помогите Поликарпу понять, какое наибольшее число подарочных наборов он может составить. </p><p>Например, если $$$x = 10$$$, $$$y = 12$$$, $$$a = 5$$$ и $$$b = 2$$$, то он может составить три подарочных набора: </p><ul> <li> В первом наборе будет $$$5$$$ красных конфет и $$$2$$$ синие; </li><li> Во втором наборе будет $$$5$$$ синих конфет и $$$2$$$ красные; </li><li> В третьем наборе будет $$$5$$$ синих конфет и $$$2$$$ красные. </li></ul><p>У Поликарпа останется одна красная конфета, используя которую, он не сможет собрать еще один подарочный набор.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор входных данных состоит из одной строки в которой находятся четыре целых числа $$$x$$$, $$$y$$$, $$$a$$$ и $$$b$$$ ($$$1 \le x, y, a, b \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно число — максимальное количество подарочных наборов, которое может собрать Поликарп.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 9 10 12 2 5 1 1 2 2 52 311 13 27 1000000000 1000000000 1 1 1000000000 1 1 1000000000 1 1000000000 1000000000 1 1 2 1 1 7 8 1 2 4 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 0 4 1000000000 1 1 1 5 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 11:29: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:'8124c683ef4a9d98',t:'MTY5NjY2NzM1Ni44NjUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u0440\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u0440\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "*2100"]
1539A
1539
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$$$ человек, причем они начинают олимпиаду с интервалом в $$$x$$$ минут. Таким образом первый участник начнёт тур в момент времени $$$0$$$, второй участник начнёт тур в момент времени $$$x$$$, третий — в момент времени $$$2 \cdot x$$$ и так далее.</p><p>Длительность тура для каждого участника составляет ровно $$$t$$$ минут, то есть первый участник закончит в момент времени $$$t$$$, второй — в момент времени $$$t + x$$$, и так далее. Когда участник заканчивает писать тур, величина его недовольства равна числу других участников, которые в текущий момент времени еще пишут или только начинают писать тур, но еще не закончили его.</p><p>Определите, чему равно суммарное недовольство всех участников олимпиады.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке вводится единственное число $$$k$$$ ($$$1 \le k \le 1000$$$) — количество наборов входных данных.</p><p>Каждая из следующих $$$k$$$ строк содержит по три целых числа $$$n$$$, $$$x$$$, $$$t$$$ ($$$1 \le n, x, t \le 2 \cdot 10^9$$$) — число участников олимпиады, интервал в минутах между временами начала тура для участников и длительность тура.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$k$$$ строк, в $$$i$$$-й из них выведите суммарное недовольство всех участников олимпиады для $$$i$$$-го набора входных данных.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 4 2 5 3 1 2 3 3 10 2000000000 1 2000000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 3 3 1999999999000000000 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных первый участник начнёт писать тур в момент времени $$$0$$$ и закончит в момент времени $$$5$$$. К этому времени второй и третий участники уже начнут писать тур, поэтому недовольство первого участника будет равно $$$2$$$. </p><p>Второй участник начнёт писать в момент времени $$$2$$$ и закончит в момент времени $$$7$$$. К этому моменту третий и четвёртый участники уже начнут писать тур, поэтому недовольство второго будет равно $$$2$$$. </p><p>Третий участник начнёт писать тур в момент времени $$$4$$$ и закончит в момент времени $$$9$$$. К этому времени четвёртый уже начнёт писать тур, поэтому недовольство третьего будет равно $$$1$$$.</p><p>Четвёртый участник начнёт писать тур в момент времени $$$6$$$ и закончит в момент времени $$$11$$$. В момент времени $$$11$$$ уже никто не будет писать тур, поэтому недовольство четвёртого будет равно $$$0$$$.</p><p>Во втором наборе входных данных первый участник начнёт писать тур в момент времени $$$0$$$ и закончит в момент времени $$$2$$$. К этому моменту второй уже будет писать тур, а третий как раз начнёт в момент времени $$$2$$$. Поэтому недовольство первого участника будет равно $$$2$$$. </p><p>Второй начнёт в момент времени $$$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="9b492031d11883970995d9fd55da6753"/> <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="3b3d6aa18ec7f2c8636f747ba32c1b3c7997564d"/> <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='9b492031d11883970995d9fd55da6753'>&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%2F1539%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='9b492031d11883970995d9fd55da6753'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1539">Codeforces Round 727 (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='9b492031d11883970995d9fd55da6753'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1539/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Геометрия"> геометрия </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *1000 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='9b492031d11883970995d9fd55da6753'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1021670"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='9b492031d11883970995d9fd55da6753'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1021670"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91905" title="Codeforces Round #727 (Div. 2, по Всероссийской олимпиаде имени Келдыша) [Рейтинговый]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13910:13911" 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/91906" title="tutorial" target="_blank">tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13923" 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/1539">Задачи</a></li> <li><a href="/contest/1539/submit">Отослать</a></li> <li><a href="/contest/1539/my">Мои посылки</a></li> <li><a href="/contest/1539/status">Статус</a></li> <li><a href="/contest/1539/hacks">Взломы</a></li> <li><a href="/contest/1539/room/1">Комната</a></li> <li><a href="/contest/1539/standings">Положение</a></li> <li><a href="/contest/1539/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_1daf3a76e8e4d412b07baf01e4198a3a11fe208d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ человек, причем они начинают олимпиаду с интервалом в $$$x$$$ минут. Таким образом первый участник начнёт тур в момент времени $$$0$$$, второй участник начнёт тур в момент времени $$$x$$$, третий — в момент времени $$$2 \cdot x$$$ и так далее.</p><p>Длительность тура для каждого участника составляет ровно $$$t$$$ минут, то есть первый участник закончит в момент времени $$$t$$$, второй — в момент времени $$$t + x$$$, и так далее. Когда участник заканчивает писать тур, величина его недовольства равна числу других участников, которые в текущий момент времени еще пишут или только начинают писать тур, но еще не закончили его.</p><p>Определите, чему равно суммарное недовольство всех участников олимпиады.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке вводится единственное число $$$k$$$ ($$$1 \le k \le 1000$$$) — количество наборов входных данных.</p><p>Каждая из следующих $$$k$$$ строк содержит по три целых числа $$$n$$$, $$$x$$$, $$$t$$$ ($$$1 \le n, x, t \le 2 \cdot 10^9$$$) — число участников олимпиады, интервал в минутах между временами начала тура для участников и длительность тура.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$k$$$ строк, в $$$i$$$-й из них выведите суммарное недовольство всех участников олимпиады для $$$i$$$-го набора входных данных.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 4 2 5 3 1 2 3 3 10 2000000000 1 2000000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 3 3 1999999999000000000 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных первый участник начнёт писать тур в момент времени $$$0$$$ и закончит в момент времени $$$5$$$. К этому времени второй и третий участники уже начнут писать тур, поэтому недовольство первого участника будет равно $$$2$$$. </p><p>Второй участник начнёт писать в момент времени $$$2$$$ и закончит в момент времени $$$7$$$. К этому моменту третий и четвёртый участники уже начнут писать тур, поэтому недовольство второго будет равно $$$2$$$. </p><p>Третий участник начнёт писать тур в момент времени $$$4$$$ и закончит в момент времени $$$9$$$. К этому времени четвёртый уже начнёт писать тур, поэтому недовольство третьего будет равно $$$1$$$.</p><p>Четвёртый участник начнёт писать тур в момент времени $$$6$$$ и закончит в момент времени $$$11$$$. В момент времени $$$11$$$ уже никто не будет писать тур, поэтому недовольство четвёртого будет равно $$$0$$$.</p><p>Во втором наборе входных данных первый участник начнёт писать тур в момент времени $$$0$$$ и закончит в момент времени $$$2$$$. К этому моменту второй уже будет писать тур, а третий как раз начнёт в момент времени $$$2$$$. Поэтому недовольство первого участника будет равно $$$2$$$. </p><p>Второй начнёт в момент времени $$$1$$$ и закончит в момент времени $$$3$$$. К этому моменту только третий будет всё ещё писать тур.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c68c1d37163d',t:'MTY5NjY2NzM1OC4yNDQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1000"]
https://codeforces.com/blog/entry/91906
<!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="c4ae3f1dbdd3aa7685e27f571fc144d8"/> <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="Codeforces Round #727 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #727 Editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='c4ae3f1dbdd3aa7685e27f571fc144d8'>&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%2F91906">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='c4ae3f1dbdd3aa7685e27f571fc144d8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:31:34</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:31:34</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='c4ae3f1dbdd3aa7685e27f571fc144d8'/> <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="92516"> <div class="title"> <a href="/blog/entry/91906"> <p>Codeforces Round #727 Editorial</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="Jun/18/2021 00:11">2 years ago</span>, translation, <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/1539/problem/A" title="Codeforces Round 727 (Div. 2)">1539A - Contest Start</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/1539/problem/B" title="Codeforces Round 727 (Div. 2)">1539B - Love Song</a> was authored by jury and prepared by <a class="rated-user user-red" href="/profile/talant" title="Grandmaster talant">talant</a></p><p><a href="/contest/1539/problem/C" title="Codeforces Round 727 (Div. 2)">1539C - Stable Groups</a> was authored by <a class="rated-user user-orange" href="/profile/Artyom123" title="International Master Artyom123">Artyom123</a> and prepared by <a class="rated-user user-orange" href="/profile/Artyom123" title="International Master Artyom123">Artyom123</a> and <a class="rated-user user-blue" href="/profile/shishyando" title="Expert shishyando">shishyando</a></p><p><a href="/contest/1539/problem/D" title="Codeforces Round 727 (Div. 2)">1539D - PriceFixed</a> was authored by Helen Andreeva and prepared by <a class="rated-user user-red" href="/profile/Siberian" title="Grandmaster Siberian">Siberian</a></p><p><a href="/contest/1539/problem/E" title="Codeforces Round 727 (Div. 2)">1539E - Game with Cards</a> was authored and prepared by <a class="rated-user user-orange" href="/profile/TeaTime" title="Master TeaTime">TeaTime</a></p><p><a href="/contest/1539/problem/F" title="Codeforces Round 727 (Div. 2)">1539F - Strange Array</a> was authored and prepared by <a class="rated-user user-orange" href="/profile/Tikhon228" title="Master Tikhon228">Tikhon228</a></p> <div class="problemTutorial" problemcode="1539A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539C">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539D">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539E">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539F">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/1539" class="notice" style="text-decoration: none;">Codeforces Round 727 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-42191-92516").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: "91906", 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> <span style="padding: 0 0.35em;"> <a href="/search?query=%23727" class="tag notice" style="text-decoration: none;">#727</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-92516"><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'>+79</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-92516"><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="Jun/18/2021 00:11">2 years ago</span> </li> <li> <a href="/blog/entry/91906#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/91906#comments"> 116 </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="100475"> <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 (81)</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="807107" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hhoppitree" style="position: relative;"> <img src='https://userpic.codeforces.org/1366950/avatar/874468310bfb5ee5.jpg'/> </a> <div><a href="/profile/hhoppitree" title="Grandmaster hhoppitree" class="rated-user user-red">hhoppitree</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 01:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807107" href="?#comment-807107" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807107" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1366950" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807107"> <div class="moveup"> <div class="ttypography"><p>A great competition with hacking :)</p></div> </div> </div> <div class="reply info"> <a class="comment-807107 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807107 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807107"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807116" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iLoveIOI" style="position: relative;"> <img src='https://userpic.codeforces.org/483613/avatar/19b4d34a35f1e022.jpg'/> </a> <div><a href="/profile/iLoveIOI" title="Master iLoveIOI" class="rated-user user-orange">iLoveIOI</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 03:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807116" href="?#comment-807116" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807116" class="CommentVoteFrame" data-commentRating="34" data-commentUserId="483613" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+34</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807116"> <div class="moveup"> <div class="ttypography"><p>Can someone explain one of the multiset solutions to E? Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-807116 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807116 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807116"> <li> <div class="comment"> <table class="comment-table" commentId="807421" commentParentId="807116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lazywitt" style="position: relative;"> <img src='https://userpic.codeforces.org/995139/avatar/e4276e734c1b167e.jpg'/> </a> <div><a href="/profile/lazywitt" title="Pupil lazywitt" class="rated-user user-green">lazywitt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 21:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807421" href="?#comment-807421" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807116" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807421" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="995139" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807421"> <div class="moveup"> <div class="ttypography"><p>Can you show any multiset solutions which passed ? </p></div> </div> </div> <div class="reply info"> <a class="comment-807421 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807421 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807421"> <li> <div class="comment"> <table class="comment-table" commentId="807448" commentParentId="807421"> <tr> <td class="left"> <div style="position: absolute; left: 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/iLoveIOI" style="position: relative;"> <img src='https://userpic.codeforces.org/483613/avatar/19b4d34a35f1e022.jpg'/> </a> <div><a href="/profile/iLoveIOI" title="Master iLoveIOI" class="rated-user user-orange">iLoveIOI</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 04:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807448" href="?#comment-807448" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807421" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807448" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="483613" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807448"> <div class="moveup"> <div class="ttypography"><p>For example, <a href="https://codeforces.com/contest/1539/submission/120110352">this</a> and <a href="https://codeforces.com/contest/1539/submission/120092916">this</a>. </p></div> </div> </div> <div class="reply info"> <a class="comment-807448 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807448 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807448"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807484" commentParentId="807116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lucaperju" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lucaperju" title="International Grandmaster lucaperju" class="rated-user user-red">lucaperju</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 09:45">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807484" href="?#comment-807484" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807116" style="font-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="807484" 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="807484" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="627011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807484"> <div class="moveup"> <div class="ttypography"><p>Consider dpL[i][j] (different from the one from the editorial) as equal to 1 if it's possible to take the first i cards, ith one in the left hand, and j being the last card we took in the right hand (j&lt;i). And, dpR[j][i] as equal to 1 if it's possible to take the first i cards, last one in the right hand, and j being the last card we took in the left hand. then, instead of storing the whole array, let L[i] be a set (or multiset) of pairs of &lt;k[j],j&gt; such that dpL[i][j] is 1, (and the same for R[i]). Now, if we're at step i and know L[i] and R[i], let's try to compute L[i+1] and R[i+1]: Let's focus on computing L[i+1], for R[i+1] it's similar: if (i+1)th card can't go in the left hand, then L[i+1] will be empty, let's assume it can go there. Let's also assume that the (i+1)th right hand can take any card, we'll fix that later. Then, first of all, if the set R[i] is not empty, we should add the pair &lt;k[i],i&gt; to L[i+1], that's because we can go from having the cards from (j, i) to (i+1, i) by taking the i+1th card in the left hand. And, let's also add to L[i+1] all the pairs from L[i], because we can get those by going from (i, j) to (i+1, j). Now, I assumed that the (i+1)th right hand can take any card, while in reality it can only take those whose k is between ar[i+1] and br[i+1]. So, let's erase from L[i+1] the pairs that are not valid. Since it's a set, we can just erase the smallest card values and the highest card values from the set which are not in the interval. This might seem like it's too slow, but it's actually amortized, because at each step, we only add at most one new pair to the set ( the pair &lt;k[i], i&gt; ), and delete some of the pairs which aren't valid. I'm not sure if I explained this very well, I hope it's clear.</p></div> </div> </div> <div class="reply info"> <a class="comment-807484 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807484 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807484"> <li> <div class="comment"> <table class="comment-table" commentId="807490" commentParentId="807484"> <tr> <td class="left"> <div style="position: absolute; left: 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/iLoveIOI" style="position: relative;"> <img src='https://userpic.codeforces.org/483613/avatar/19b4d34a35f1e022.jpg'/> </a> <div><a href="/profile/iLoveIOI" title="Master iLoveIOI" class="rated-user user-orange">iLoveIOI</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 10:26">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807490" href="?#comment-807490" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807484" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807490" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="483613" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807490"> <div class="moveup"> <div class="ttypography"><p>Ah, I see thanks a lot! It was very clear :)</p></div> </div> </div> <div class="reply info"> <a class="comment-807490 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807490 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807490"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807916" commentParentId="807484"> <tr> <td class="left"> <div style="position: absolute; left: 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/Mrajaryan" style="position: relative;"> <img src='https://userpic.codeforces.org/1377953/avatar/e904b3a3a2eac1ad.jpg'/> </a> <div><a href="/profile/Mrajaryan" title="Newbie Mrajaryan" class="rated-user user-gray">Mrajaryan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 13:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807916" href="?#comment-807916" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807484" style="font-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="807916" 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="807916" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1377953" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807916"> <div class="moveup"> <div class="ttypography"><p>Thanks for explanation. But I can't understand why I should use dp? Can you please give some idea on this ? Or just tell me the naive approach by which i can solve the problem? Like naive dp approach</p></div> </div> </div> <div class="reply info"> <a class="comment-807916 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807916 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807916"> <li> <div class="comment"> <table class="comment-table" commentId="807995" commentParentId="807916"> <tr> <td class="left"> <div style="position: absolute; left: 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/lucaperju" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lucaperju" title="International Grandmaster lucaperju" class="rated-user user-red">lucaperju</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 17:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807995" href="?#comment-807995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807916" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807995" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="627011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807995"> <div class="moveup"> <div class="ttypography"><p>A naive dp approach using the same dp I described above would be: dpL[i][j] (j&lt;i) is true if, obviously, ith card can stay in the left hand (at step i), and jth card can stay in the right hand (at step i), and either:</p> <ul> <li><p>j &lt; (i-1), and dpL[i-1][j] is true</p></li> <li><p>OR j == (i-1), and there exists such k &lt; (i-1) so that dpR[k][i-1] is true</p></li> </ul><p>And similarly for dpR. After calculating this, you can easily recreate the solution from right to left.</p></div> </div> </div> <div class="reply info"> <a class="comment-807995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807995"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="810899" commentParentId="807484"> <tr> <td class="left"> <div style="position: absolute; left: 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/vishaaaal" style="position: relative;"> <img src='https://userpic.codeforces.org/1443354/avatar/25a2dd924894eeeb.jpg'/> </a> <div><a href="/profile/vishaaaal" title="Expert vishaaaal" class="rated-user user-blue">vishaaaal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/02/2021 20:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810899" href="?#comment-810899" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807484" style="font-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="810899" 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="810899" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1443354" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-810899"> <div class="moveup"> <div class="ttypography"><p>How will the following be represented according to these dp states?</p><p>We can pick all the cards upto the ith card in the left hand but none of them in the right hand (in other words, all the queries are answered on the left hand upto the ith card). </p><p>This would imply that there is no j such that dpL[i][j] is 1. But still we can answer all the queries upto the ith card.</p><p>Edit: I thought a lil bit about it and I think we can use 0 as a dummy card (which basically means, by default we'll have 0 as a card in right hand if we don't pick any card in it). And yess, AC. Great explanation OFZ.</p></div> </div> </div> <div class="reply info"> <a class="comment-810899 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810899 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810899"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807117" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Acfboy" style="position: relative;"> <img src='https://userpic.codeforces.org/873793/avatar/146c53315bccb6e9.jpg'/> </a> <div><a href="/profile/Acfboy" title="Master Acfboy" class="rated-user user-orange">Acfboy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 03:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807117" href="?#comment-807117" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807117" class="CommentVoteFrame" data-commentRating="61" data-commentUserId="873793" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+61</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807117"> <div class="moveup"> <div class="ttypography"><p>Nice problems, but the gap between problem ABCD and EF seems too large.</p></div> </div> </div> <div class="reply info"> <a class="comment-807117 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807117 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807117"> <li> <div class="comment"> <table class="comment-table" commentId="807121" commentParentId="807117"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807121" href="?#comment-807121" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807117" style="font-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="807121" 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="807121" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807121"> <div class="moveup"> <div class="ttypography"><p>I think there is a mistake in the editorial of the Problem F.</p><p>The editorial said if the $$$a_i$$$ is less than or equal to the median element then $$$ans = \left\lfloor\dfrac{cnt_R+cnt_M-cnt_L+1}{2} \right\rfloor$$$, but if I have an array that is $$$[1, 2, 3, 4, 4, 6]$$$, the ans of the number $$$4$$$ should be 1, and if you use the formula mentioned above, you may get a wrong answer 0.</p><p>Could anyone tell me the correct formula?</p></div> </div> </div> <div class="reply info"> <a class="comment-807121 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807121 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807121"> <li> <div class="comment"> <table class="comment-table" commentId="807156" commentParentId="807121"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807156" href="?#comment-807156" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807121" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807156" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807156"> <div class="moveup"> <div class="ttypography"><p>The formula is correct, but it's for when the element come to the left of median. When element comes to right of median, other formula should be used which should give you 1. That's why we should take maximum from left &amp; right.</p></div> </div> </div> <div class="reply info"> <a class="comment-807156 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807156 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807156"> <li> <div class="comment"> <table class="comment-table" commentId="807196" commentParentId="807156"> <tr> <td class="left"> <div style="position: absolute; left: 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/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807196" href="?#comment-807196" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807156" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807196" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807196"> <div class="moveup"> <div class="ttypography"><p>Thank you very much. You're right and I have solved this problem by using two distinct formulas. </p></div> </div> </div> <div class="reply info"> <a class="comment-807196 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807196 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807196"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807159" commentParentId="807121"> <tr> <td class="left"> <div style="position: absolute; left: 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/Ka1hatsu" style="position: relative;"> <img src='https://userpic.codeforces.org/761494/avatar/5d5b8ffd577a29a8.jpg'/> </a> <div><a href="/profile/Ka1hatsu" title="Pupil Ka1hatsu" class="rated-user user-green">Ka1hatsu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807159" href="?#comment-807159" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807121" style="font-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="807159" 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="807159" class="CommentVoteFrame" data-commentRating="-6" data-commentUserId="761494" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807159"> <div class="moveup"> <div class="ttypography"><p>sorry</p></div> </div> </div> <div class="reply info"> <a class="comment-807159 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807159 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807159"> <li> <div class="comment"> <table class="comment-table" commentId="807192" commentParentId="807159"> <tr> <td class="left"> <div style="position: absolute; left: 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/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807192" href="?#comment-807192" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807159" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807192" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807192"> <div class="moveup"> <div class="ttypography"><p>I'm sorry but the median number is 4 according to the Problem F.</p></div> </div> </div> <div class="reply info"> <a class="comment-807192 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807192 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807192"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807120" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/highighiq" style="position: relative;"> <img src='https://userpic.codeforces.org/1420719/avatar/97be0e366e499727.jpg'/> </a> <div><a href="/profile/highighiq" title="Master highighiq" class="rated-user user-orange">highighiq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807120" href="?#comment-807120" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807120" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="1420719" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807120"> <div class="moveup"> <div class="ttypography"><p>Good problems!(But E,F is too difficult!) And I get to expert!</p></div> </div> </div> <div class="reply info"> <a class="comment-807120 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807120 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807120"> <li> <div class="comment"> <table class="comment-table" commentId="807122" commentParentId="807120"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807122" href="?#comment-807122" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807120" style="font-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="807122" 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="807122" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807122"> <div class="moveup"> <div class="ttypography"><p>Congratulations!</p></div> </div> </div> <div class="reply info"> <a class="comment-807122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807122"> <li> <div class="comment"> <table class="comment-table" commentId="807125" commentParentId="807122"> <tr> <td class="left"> <div style="position: absolute; left: 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/highighiq" style="position: relative;"> <img src='https://userpic.codeforces.org/1420719/avatar/97be0e366e499727.jpg'/> </a> <div><a href="/profile/highighiq" title="Master highighiq" class="rated-user user-orange">highighiq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:12">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807125" href="?#comment-807125" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807122" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807125" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1420719" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807125"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-807125 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807125 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807125"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807124" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hithu" style="position: relative;"> <img src='https://userpic.codeforces.org/202138/avatar/c537257b9e17f402.jpg'/> </a> <div><a href="/profile/hithu" title="Pupil hithu" class="rated-user user-green">hithu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:09">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807124" href="?#comment-807124" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="202138" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807124"> <div class="moveup"> <div class="ttypography"><p>Still don't understand editorial of D, can anybody explain the two pointer technique?</p></div> </div> </div> <div class="reply info"> <a class="comment-807124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807124"> <li> <div class="comment"> <table class="comment-table" commentId="807128" commentParentId="807124"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Enigma20" style="position: relative;"> <img src='https://userpic.codeforces.org/1301418/avatar/3ba73a2cb1eeb8ef.jpg'/> </a> <div><a href="/profile/Enigma20" title="Expert Enigma20" class="rated-user user-blue">Enigma20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807128" href="?#comment-807128" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807124" style="font-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="807128" 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="807128" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="1301418" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807128"> <div class="moveup"> <div class="ttypography"><p>First we sort the array according to increasing order of $$$b_i$$$. Now, we maintain 2 pointers one at the start of the array(say $$$i$$$) and other one at the end(say $$$j$$$). Also, let's maintain two variables $$$cur$$$(stores number of products already taken), $$$ans$$$(stores the required answer).</p><p>Now, we run a loop until $$$i\leq j$$$.</p><p>If $$$cur\geq b_i$$$, there is no point to leave this product, so we buy all $$$a_i$$$ products with 50% discount and update our $$$cur$$$ and $$$ans$$$.</p><p>If $$$cur\lt b_i$$$, then we start from second pointer i.e. $$$j$$$ and keep taking $$$min(b_i-cur,a_j)$$$ products for 2 rubles, if $$$cur\lt b_j$$$, otherwise for 1 ruble. We stop once we have $$$cur\geq b_i$$$. Update $$$cur,ans,a_j$$$ accordingly. If $$$a_j=0$$$, decrement $$$j$$$.</p><p><a href="https://codeforces.com/contest/1539/submission/120108298">My submission</a></p><p>In this submission, I ran a loop until $$$i\lt j$$$ and checked $$$i=j$$$ condition separately but that isn't necessary.</p></div> </div> </div> <div class="reply info"> <a class="comment-807128 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807128 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807128"> <li> <div class="comment"> <table class="comment-table" commentId="807155" commentParentId="807128"> <tr> <td class="left"> <div style="position: absolute; left: 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/crozzhtt" style="position: relative;"> <img src='https://userpic.codeforces.org/1592985/avatar/ea9a2bfb02b015fb.jpg'/> </a> <div><a href="/profile/crozzhtt" title="Newbie crozzhtt" class="rated-user user-gray">crozzhtt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807155" href="?#comment-807155" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807128" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807155" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1592985" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807155"> <div class="moveup"> <div class="ttypography"><p>but when cur &lt; bi I wonder if I can choose to continue buying (i-1)th product for 1 ruble or buying j-th product for 2 rubles. Will the 2nd option be more optimal than the 1st option?</p></div> </div> </div> <div class="reply info"> <a class="comment-807155 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807155 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807155"> <li> <div class="comment"> <table class="comment-table" commentId="807161" commentParentId="807155"> <tr> <td class="left"> <div style="position: absolute; left: 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/Enigma20" style="position: relative;"> <img src='https://userpic.codeforces.org/1301418/avatar/3ba73a2cb1eeb8ef.jpg'/> </a> <div><a href="/profile/Enigma20" title="Expert Enigma20" class="rated-user user-blue">Enigma20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807161" href="?#comment-807161" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807155" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807161" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1301418" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807161"> <div class="moveup"> <div class="ttypography"><p>Yes, second case will be optimal. Look at it this way, you have to buy as many products for 50% discount as possible. Now we know $$$i^{th}$$$ product has smaller $$$b_i$$$, so the condition for discount of this product will be fulfilled by taking lesser number of products for 2 rubles. Also it may happen that after taking $$$i^{th}$$$ product for 50% discount, products with higher $$$b_i$$$ can be taken for 50% discount without additional cost of 2 rubles. So, 2nd case will be optimal.</p></div> </div> </div> <div class="reply info"> <a class="comment-807161 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807161 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807161"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807130" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/avdp" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/avdp" title="Newbie avdp" class="rated-user user-gray">avdp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807130" href="?#comment-807130" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807130" class="CommentVoteFrame" data-commentRating="97" data-commentUserId="1840186" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+97</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807130"> <div class="moveup"> <div class="ttypography"><p><img alt=" " src="/predownloaded/0d/c4/0dc4ee86562ac0c8d31bcf482bed113f62f1fda1.jpg" style="max-width: 100.0%;max-height: 100.0%;" /></p><p><a class="rated-user user-red" href="/profile/galen_colin" title="Международный гроссмейстер galen_colin">galen_colin</a> <strong>too</strong></p></div> </div> </div> <div class="reply info"> <a class="comment-807130 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807130 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807130"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807132" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Atomsky" style="position: relative;"> <img src='https://userpic.codeforces.org/336914/avatar/2c5685b756a63503.jpg'/> </a> <div><a href="/profile/Atomsky" title="Newbie Atomsky" class="rated-user user-gray">Atomsky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807132" href="?#comment-807132" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807132" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="336914" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807132"> <div class="moveup"> <div class="ttypography"><p>I submitted <a href="/contest/1539/submission/120147862" title="Посылка 120147862 от Atomsky">120147862</a> for Problem-C. It gave a wrong result on test 62 in GNU C++17. When I submitted the same code in C++11, it was accepted (<a href="/contest/1539/submission/120149347" title="Посылка 120149347 от Atomsky">120149347</a>).</p><p>It would be helpful if anyone tells me what went wrong in my code.</p></div> </div> </div> <div class="reply info"> <a class="comment-807132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807132"> <li> <div class="comment"> <table class="comment-table" commentId="807136" commentParentId="807132"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/avdp" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/avdp" title="Newbie avdp" class="rated-user user-gray">avdp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 06:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807136" href="?#comment-807136" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807136" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1840186" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807136"> <div class="moveup"> <div class="ttypography"><p>Hey there, It is because of precision error differences in C++11 and C++17, So it is always advised to use <strong>long double</strong> instead of <strong>double</strong>. You will get AC in both versions with <strong>long double</strong>.</p></div> </div> </div> <div class="reply info"> <a class="comment-807136 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807136 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807136"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807165" commentParentId="807132"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/maskman_lucifer" style="position: relative;"> <img src='https://userpic.codeforces.org/1453975/avatar/e7e8769e223b3ab9.jpg'/> </a> <div><a href="/profile/maskman_lucifer" title="Pupil maskman_lucifer" class="rated-user user-green">maskman_lucifer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807165" href="?#comment-807165" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807165" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1453975" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807165"> <div class="moveup"> <div class="ttypography"><p>In these cases use this (val + d-1 )/ d instead of some ceil on double (Try to avoid doubles if you can do the same with int (precision issue)).<br /> In your case foo[i] = (jar[i] — jar[i-1] + x-1)/x will be good to go.</p></div> </div> </div> <div class="reply info"> <a class="comment-807165 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807165 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807165"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807144" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/UpMing" style="position: relative;"> <img src='https://userpic.codeforces.org/1424136/avatar/2e9bc60a07619853.jpg'/> </a> <div><a href="/profile/UpMing" title="Candidate Master UpMing" class="rated-user user-violet">UpMing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 06:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807144" href="?#comment-807144" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807144" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="1424136" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807144"> <div class="moveup"> <div class="ttypography"><p>The difficulty range is very large,</p><p>For example, D through E</p></div> </div> </div> <div class="reply info"> <a class="comment-807144 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807144 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807144"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807157" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hurt_FOR_heart" style="position: relative;"> <img src='https://userpic.codeforces.org/1445761/avatar/4bd86d3c8cfb747a.jpg'/> </a> <div><a href="/profile/hurt_FOR_heart" title="Candidate Master hurt_FOR_heart" class="rated-user user-violet">hurt_FOR_heart</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807157" href="?#comment-807157" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807157" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="1445761" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807157"> <div class="moveup"> <div class="ttypography"><p>In problem E, i thing that it's hard to come up with such dp state. Does anyone have a more natural idea for this problem ? </p></div> </div> </div> <div class="reply info"> <a class="comment-807157 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807157 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807157"> <li> <div class="comment"> <table class="comment-table" commentId="807183" commentParentId="807157"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/andr14142" style="position: relative;"> <img src='https://userpic.codeforces.org/620444/avatar/368d81a28bf4f89b.jpg'/> </a> <div><a href="/profile/andr14142" title="Pupil andr14142" class="rated-user user-green">andr14142</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 08:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807183" href="?#comment-807183" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807157" style="font-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="807183" revisionCount="7" revision="7"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">7</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="807183" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="620444" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807183"> <div class="moveup"> <div class="ttypography"><p>A more natural idea is to calculate limits for both hands from the end.<br /> Last move has no limits. The range for both hands of last move is from 0 to m inclusive.<br /> For the previous move check cases. Initially limits impossible m &lt; k &lt; 0.<br /> If you can take the card into left hand, then check, could you keep your right hand for the next move? If left card may be kept, limits for the right hand are the current limits for right hand. Otherwise right hand must be kept for the next move, so intersect current limits for right hand with limits for next move.<br /> The same for the right hand.<br /> Finally we check limits for initial situation, is pair (0,0) allowed.</p></div> </div> </div> <div class="reply info"> <a class="comment-807183 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807183 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807183"> <li> <div class="comment"> <table class="comment-table" commentId="807186" commentParentId="807183"> <tr> <td class="left"> <div style="position: absolute; left: 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/rag-hav" style="position: relative;"> <img src='https://userpic.codeforces.org/1809311/avatar/8456dc0c30997ac5.jpg'/> </a> <div><a href="/profile/rag-hav" title="Expert rag-hav" class="rated-user user-blue">rag-hav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807186" href="?#comment-807186" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807183" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807186" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1809311" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807186"> <div class="moveup"> <div class="ttypography"><p>Isn't that exponential complexity? (two choices in every move)</p></div> </div> </div> <div class="reply info"> <a class="comment-807186 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807186 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807186"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807171" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/deletha" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/deletha" title="Pupil deletha" class="rated-user user-green">deletha</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807171" href="?#comment-807171" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807171" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1806788" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807171"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1539/submission/120173484" title="Посылка 120173484 от deletha">120173484</a> I am getting runtime error on test 23 in problem C. Unable to understand if it is due to seg fault or overflows. Can someone pls explain</p></div> </div> </div> <div class="reply info"> <a class="comment-807171 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807171 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807171"> <li> <div class="comment"> <table class="comment-table" commentId="807178" commentParentId="807171"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HowSoOrz" style="position: relative;"> <img src='https://userpic.codeforces.org/1519509/avatar/24d272c5a2a620a1.jpg'/> </a> <div><a href="/profile/HowSoOrz" title="Specialist HowSoOrz" class="rated-user user-cyan">HowSoOrz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 08:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807178" href="?#comment-807178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807171" style="font-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="807178" 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="807178" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1519509" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807178"> <div class="moveup"> <div class="ttypography"><p>Just return when the valid array size is 0. You cant use binary search when the size of the valid vector is 0. Reason: v.begin()=points to first element, v.end() points to next element of last ele.</p><p><a href="/contest/1539/submission/120176292" title="Посылка 120176292 от HowSoOrz">120176292</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807178"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807185" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noobKunal" style="position: relative;"> <img src='https://userpic.codeforces.org/1183443/avatar/73aa8f3ddfbcab8a.jpg'/> </a> <div><a href="/profile/noobKunal" title="Expert noobKunal" class="rated-user user-blue">noobKunal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807185" href="?#comment-807185" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807185" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1183443" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807185"> <div class="moveup"> <div class="ttypography"><p>Can anyone check <a href="https://codeforces.com/contest/1539/submission/120132934">my submission</a> for D. Its giving TLE at tc 11 and it seems that its because of initial sorting itself (and not even entering while loop).</p></div> </div> </div> <div class="reply info"> <a class="comment-807185 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807185 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807185"> <li> <div class="comment"> <table class="comment-table" commentId="807194" commentParentId="807185"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/i_aM_SnEhaal" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/i_aM_SnEhaal" title="Pupil i_aM_SnEhaal" class="rated-user user-green">i_aM_SnEhaal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807194" href="?#comment-807194" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807185" style="font-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="807194" 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="807194" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1279863" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807194"> <div class="moveup"> <div class="ttypography"><p>I tried to submit your solution with just by changing the compare function in sort and it worked. <a href="https://codeforces.com/contest/1539/submission/120179243">Here is the submission have a look</a> just compare it with your solution to see the changes I made.The problem was in how you are defining the compare function in sort. What I have understood is &lt;= or &gt;= is slower than &lt; or &gt; which is causing the problem. For more details please go through <a href="https://codeforces.com/blog/entry/70237">this blog</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-807194 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807194 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807194"> <li> <div class="comment"> <table class="comment-table" commentId="807201" commentParentId="807194"> <tr> <td class="left"> <div style="position: absolute; left: 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/noobKunal" style="position: relative;"> <img src='https://userpic.codeforces.org/1183443/avatar/73aa8f3ddfbcab8a.jpg'/> </a> <div><a href="/profile/noobKunal" title="Expert noobKunal" class="rated-user user-blue">noobKunal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807201" href="?#comment-807201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807194" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807201" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1183443" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807201"> <div class="moveup"> <div class="ttypography"><p>Thanks it passed. Wish i've known this before</p></div> </div> </div> <div class="reply info"> <a class="comment-807201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807201"> <li> <div class="comment"> <table class="comment-table" commentId="807205" commentParentId="807201"> <tr> <td class="left"> <div style="position: absolute; left: 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/i_aM_SnEhaal" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/i_aM_SnEhaal" title="Pupil i_aM_SnEhaal" class="rated-user user-green">i_aM_SnEhaal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807205" href="?#comment-807205" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807205" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1279863" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807205"> <div class="moveup"> <div class="ttypography"><p>I also learnt it the hard way. After getting TLE on TC 11 twice during the contest and then submitting the same code in 8 different ways after the contest was able to figure it out. </p></div> </div> </div> <div class="reply info"> <a class="comment-807205 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807205 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807205"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="1035068" commentParentId="807194"> <tr> <td class="left"> <div style="position: absolute; left: 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/BDboy" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BDboy" title="Expert BDboy" class="rated-user user-blue">BDboy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/05/2023 21:16">4 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1035068" href="?#comment-1035068" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807194" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1035068" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2468471" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1035068"> <div class="moveup"> <div class="ttypography"><p>Thanks, I wont be learning this the hard way. :)</p></div> </div> </div> <div class="reply info"> <a class="comment-1035068 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1035068 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1035068"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807188" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vkgainz" style="position: relative;"> <img src='https://userpic.codeforces.org/679880/avatar/f966b85a769e4f5.jpg'/> </a> <div><a href="/profile/vkgainz" title="Grandmaster vkgainz" class="rated-user user-red">vkgainz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:12">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807188" href="?#comment-807188" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807188" class="CommentVoteFrame" data-commentRating="51" data-commentUserId="679880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+51</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807188"> <div class="moveup"> <div class="ttypography"><p>I found D to be a lot easier to think about using binary search (which solves in $$$O(n\log(10^{14}))$$$. Similar to the editorial, sort with respect to $$$b_i$$$. Now, let $$$x$$$ be the number of items with price $$$1$$$ and $$$y$$$ be the number of items with price $$$2$$$. Then, our answer is equal to $$$x + 2 \cdot y = y + \sum_{i = 1} ^ {n} a_i$$$, so it suffices to minimize $$$y$$$.</p><p>Let's binary search on this. Suppose we set $$$y = k$$$. How do we know if this is enough? First we make two simple observations:</p> <ul> <li><p>We buy all $$$k$$$ items at the very beginning.</p></li> <li><p>We buy all $$$k$$$ items from a suffix of the sorted array.</p></li> </ul><p>Why does this work? Well, if you are going to buy $$$k$$$ items of price $$$2$$$, you should do it earlier than later, because then we might have more $$$b_i$$$ opened up that gives us items of price $$$1$$$. Similarly, we should be buying our items from a suffix because that way we can maximize the number of items of price $$$1$$$ we get (and, subsequently, minimize the number of items of price $$$2$$$). </p><p>From here it's simple to solve with binary search. To test $$$y = k$$$, start a counter for the number of items bought and an index at $$$0$$$. While the counter is greater than $$$b_{\text{index}}$$$, add $$$a_{\text{index}}$$$ to the counter (since we're getting all of those for price $$$1$$$) and increment the counter. If $$$k$$$ is enough, then the counter should be $$$\geq$$$ the number of items we have in total.</p><p>This explanation may seem a bit complicated, but the ideas involved are simple to arrive at and the implementation is very clean: <a href="https://codeforces.com/contest/1539/submission/120179122">my submission here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-807188 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807188 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807188"> <li> <div class="comment"> <table class="comment-table" commentId="807238" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ace-in-the-hole" style="position: relative;"> <img src='https://userpic.codeforces.org/725810/avatar/31d6d37857b526e4.jpg'/> </a> <div><a href="/profile/ace-in-the-hole" title="Candidate Master ace-in-the-hole" class="rated-user user-violet">ace-in-the-hole</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 12:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807238" href="?#comment-807238" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807238" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="725810" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807238"> <div class="moveup"> <div class="ttypography"><p>This idea is nice, but it's still not too different from the solution, because we still have to make the observation: buying items with higher b_i is better. I can say, your idea is <strong>not fundamentally different</strong> from the solution's idea. Maybe because this is not a hard problem so we can't see the diversity of the solutions like some others.</p><p>But it sure is a great idea, the thoughts &quot;I should minimize the number of bought items with price 2&quot;, &quot;I can binary search the answer on this&quot;, ... and more, as you explained, are completely natural and can be thought of. Thank you for your contribution!</p></div> </div> </div> <div class="reply info"> <a class="comment-807238 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807238 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807238"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807334" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/faraz16iqbal" style="position: relative;"> <img src='https://userpic.codeforces.org/1534426/avatar/6269999f6a6fd0c7.jpg'/> </a> <div><a href="/profile/faraz16iqbal" title="Expert faraz16iqbal" class="rated-user user-blue">faraz16iqbal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 17:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807334" href="?#comment-807334" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807334" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1534426" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807334"> <div class="moveup"> <div class="ttypography"><p>Thank you, brilliant explanation</p></div> </div> </div> <div class="reply info"> <a class="comment-807334 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807334 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807334"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807893" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeerInForestovo" style="position: relative;"> <img src='https://userpic.codeforces.org/805889/avatar/8210f0230414d9cc.jpg'/> </a> <div><a href="/profile/DeerInForestovo" title="Master DeerInForestovo" class="rated-user user-orange">DeerInForestovo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 12:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807893" href="?#comment-807893" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807893" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="805889" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807893"> <div class="moveup"> <div class="ttypography"><p>Thanks. In your solution, we finally found a proper position where the things before it were 1 and later than it were 2. So, why not check every possible position and keep some useful information? See <a href="https://codeforces.com/contest/1539/submission/120329507">my submission</a>, which is theoretically O(N) if we use radix sort instead of qsort.</p><p>Sorry for my bad English : )</p></div> </div> </div> <div class="reply info"> <a class="comment-807893 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807893 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807893"> <li> <div class="comment"> <table class="comment-table" commentId="807895" commentParentId="807893"> <tr> <td class="left"> <div style="position: absolute; left: 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/DeerInForestovo" style="position: relative;"> <img src='https://userpic.codeforces.org/805889/avatar/8210f0230414d9cc.jpg'/> </a> <div><a href="/profile/DeerInForestovo" title="Master DeerInForestovo" class="rated-user user-orange">DeerInForestovo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 12:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807895" href="?#comment-807895" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807893" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807895" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="805889" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807895"> <div class="moveup"> <div class="ttypography"><p>In my submission, 'Hab' meant 'Had bought'</p></div> </div> </div> <div class="reply info"> <a class="comment-807895 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807895 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807895"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="868233" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yeetholmes619" style="position: relative;"> <img src='https://userpic.codeforces.org/1957631/avatar/1ad3067143e8096e.jpg'/> </a> <div><a href="/profile/yeetholmes619" title="Expert yeetholmes619" class="rated-user user-blue">yeetholmes619</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/17/2021 01:45">22 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-868233" href="?#comment-868233" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="868233" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1957631" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-868233"> <div class="moveup"> <div class="ttypography"><p>I'm sorry for replying to your comment that is 6 months old, but reading this cleared all my doubts and troubles with this problem, I struggled with finding the right train of thought to solve this problem and the way you explained it removed all of my confusion regarding this.</p><p>The two pointer technique althought gives AC, didn't make the underlying idea behind the solution, i.e x+2y will be our minimum cost which can be re-written as ∑ai + y obvious to me, which your approach clearly does. Thanks a lot! your comment not only helped me in this problem but will help me in future problems as well as it gave light to the right mindset while solving the problem :)</p></div> </div> </div> <div class="reply info"> <a class="comment-868233 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-868233 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-868233"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807217" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Delver0227" style="position: relative;"> <img src='https://userpic.codeforces.org/1594171/avatar/5f6e96d412ba3fde.jpg'/> </a> <div><a href="/profile/Delver0227" title="Specialist Delver0227" class="rated-user user-cyan">Delver0227</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 10:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807217" href="?#comment-807217" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807217" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1594171" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807217"> <div class="moveup"> <div class="ttypography"><p>I have a different way of implementing problem D that is more concise. Considering buying items backwards, we want to the last item we buy is the item with the highest discount requirement(which can be achieved). Which means all we need to do is suppose we have already bought all the items and the number of items is $$$num$$$. Sorting $$$b_i$$$ in non-decreasing order, skip the items that are impossible to get a discount on and take $$$num_i = \min(num-b_i,a_i)$$$ as the number of $$$item_i$$$ which we can buy with a discount. Remember to substract $$$num_i$$$ from $$$num$$$. After iterating $$$i$$$ through all the items, the sum of $$$num_i$$$ is the total number of item that we can get a discount on.</p><p>The code goes like this:<a href="https://paste.ubuntu.com/p/8mwW8n2yfQ/">https://paste.ubuntu.com/p/8mwW8n2yfQ/</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807217 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807217 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807217"> <li> <div class="comment"> <table class="comment-table" commentId="809490" commentParentId="807217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Whimpers" style="position: relative;"> <img src='https://userpic.codeforces.org/1507315/avatar/b11dc9bbdf35d8d9.jpg'/> </a> <div><a href="/profile/Whimpers" title="Expert Whimpers" class="rated-user user-blue">Whimpers</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 03:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809490" href="?#comment-809490" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809490" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1507315" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809490"> <div class="moveup"> <div class="ttypography"><p>why does this work? dont 1's also count towards the total items bought. from what i can see from your solution it is just comparing if the number of items left is greater than the b of the current last item, but if there is an item that has a lot more a than it has b, wouldnt it also be useful in increasing the total number bought and thus would have to be used in the total number of items bought?</p></div> </div> </div> <div class="reply info"> <a class="comment-809490 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809490 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809490"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807229" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Samrev" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Samrev" title="Expert Samrev" class="rated-user user-blue">Samrev</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 11:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807229" href="?#comment-807229" style="font-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="807229" 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="807229" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="1932888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807229"> <div class="moveup"> <div class="ttypography"><p>Test:</p> <pre><code>5 3 10 2 12 1 11 3 10 1 8 </code></pre><p>Submission: <a href="/contest/1539/submission/120129309" title="Посылка 120129309 от Kakashi_099">120129309</a></p><p>Output : 20 Correct Output: 19</p><p>This submission is getting accepted but however the above test case shows wrong output. Correct Output should be 19, instead of 20.</p><p><a class="rated-user user-red" href="/profile/talant" title="Гроссмейстер talant">talant</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807229 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807229 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807229"> <li> <div class="comment"> <table class="comment-table" commentId="807256" commentParentId="807229"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/talant" style="position: relative;"> <img src='https://userpic.codeforces.org/1215930/avatar/cc80e217f41ccfb0.jpg'/> </a> <div><a href="/profile/talant" title="Grandmaster talant" class="rated-user user-red">talant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807256" href="?#comment-807256" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807229" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807256" class="CommentVoteFrame" data-commentRating="58" data-commentUserId="1215930" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+58</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807256"> <div class="moveup"> <div class="ttypography"><p>Stop tagging me, this task isn't even mine</p></div> </div> </div> <div class="reply info"> <a class="comment-807256 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807256 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807256"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807232" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Anish_Bashyal" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Anish_Bashyal" title="Pupil Anish_Bashyal" class="rated-user user-green">Anish_Bashyal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 12:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807232" href="?#comment-807232" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807232" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1411502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807232"> <div class="moveup"> <div class="ttypography"><p><strong>Problem D</strong></p><p>Proof that buying more items of some product than needed doesn't make the answer better. Let's suppose we have already achieved an product (say product A) which we can buy at discount. Now consider we have to buy next product (say product B). </p><p><strong>N</strong> be the number of product B we have to buy, and <strong>d</strong> be the total purchases required before discount and <strong>c</strong> be the amount of items we have already purchased. Then, </p><p><strong>Case I (buy more of product A and then B)</strong></p><p>Total cost for buying product B = <strong>(d-c)*1 + (N*1)</strong> = <strong>d-c+N</strong></p><p><strong>Case II (only buying product B)</strong></p><p>Total cost for buying product B = <strong>2 * (d-c) + ( N-( d-c ) )</strong> = <strong>d-c+N</strong> </p><p>So both the cases cost the same. But this is a special scenario. If we had different percentage of discount, then the above cases wouldn't be equal. </p><p>If we say <strong>m</strong> as discount percentage and <strong>x</strong> as normal price then, </p><p><strong>Case I</strong></p><p><em>mx(d-c) + Nmx</em></p><p><strong>Case II</strong></p><p><em>x(d-c) + (N-d+c)mx</em></p><p>Equating both cases, we get <strong>m = 0.5 or 50%</strong>..</p><p>So only when the discount percentage is 50%, buying more of a discounted product or buying only the required quantity of each products doesn't matter. Hence also in this case, doesn't matter.</p><p>Sorry for writing just the obvious algebra but wanted to share anyway :)</p></div> </div> </div> <div class="reply info"> <a class="comment-807232 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807232 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807232"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807240" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hurt_FOR_heart" style="position: relative;"> <img src='https://userpic.codeforces.org/1445761/avatar/4bd86d3c8cfb747a.jpg'/> </a> <div><a href="/profile/hurt_FOR_heart" title="Candidate Master hurt_FOR_heart" class="rated-user user-violet">hurt_FOR_heart</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807240" href="?#comment-807240" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807240" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="1445761" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807240"> <div class="moveup"> <div class="ttypography"><p>in E</p> <ul> <li>Card in query i fits constraints on value written on card in left hand in queries with indexes [i,j).</li> </ul><p>i think it's [i,j] isn't it ? Because we have card in i for query j too </p></div> </div> </div> <div class="reply info"> <a class="comment-807240 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807240 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807240"> <li> <div class="comment"> <table class="comment-table" commentId="807271" commentParentId="807240"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TeaTime" style="position: relative;"> <img src='https://userpic.codeforces.org/1199093/avatar/f1cbbd424f7d3cf7.jpg'/> </a> <div><a href="/profile/TeaTime" title="Master TeaTime" class="rated-user user-orange">TeaTime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:25">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807271" href="?#comment-807271" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807240" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807271" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="1199093" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807271"> <div class="moveup"> <div class="ttypography"><p>It's [i, j) because card j was already taken in right hand.</p></div> </div> </div> <div class="reply info"> <a class="comment-807271 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807271 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807271"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807273" commentParentId="807240"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TeaTime" style="position: relative;"> <img src='https://userpic.codeforces.org/1199093/avatar/f1cbbd424f7d3cf7.jpg'/> </a> <div><a href="/profile/TeaTime" title="Master TeaTime" class="rated-user user-orange">TeaTime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807273" href="?#comment-807273" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807240" style="font-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="807273" 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="807273" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="1199093" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807273"> <div class="moveup"> <div class="ttypography"><p>Oh, you are correct, I mistook it with something else. Thanks for noticing!</p><p>Edit: editorial was fixed.</p></div> </div> </div> <div class="reply info"> <a class="comment-807273 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807273 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807273"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807241" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pucuk16" style="position: relative;"> <img src='https://userpic.codeforces.org/1458650/avatar/a688a695b97d78cb.jpg'/> </a> <div><a href="/profile/pucuk16" title="Newbie pucuk16" class="rated-user user-gray">pucuk16</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807241" href="?#comment-807241" style="font-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="807241" 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="807241" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1458650" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807241"> <div class="moveup"> <div class="ttypography"><p>hai.. where my code gone wrong..? please help me..<br /> for problem C <br /> thx <a href="https://codeforces.com/contest/1539/submission/120116110">code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807241"> <li> <div class="comment"> <table class="comment-table" commentId="807335" commentParentId="807241"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bwxnQAQ" style="position: relative;"> <img src='https://userpic.codeforces.org/1816180/avatar/1179db2c2821d194.jpg'/> </a> <div><a href="/profile/bwxnQAQ" title="Expert bwxnQAQ" class="rated-user user-blue">bwxnQAQ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 17:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807335" href="?#comment-807335" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807241" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807335" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="1816180" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807335"> <div class="moveup"> <div class="ttypography"><p>You should check line 37.You change d continuously without initializing.The d on the right side of each formula in line 37 should be the d in line 32 instead of the last calculated d.</p></div> </div> </div> <div class="reply info"> <a class="comment-807335 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807335 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807335"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807251" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spookywooky" style="position: relative;"> <img src='https://userpic.codeforces.org/872585/avatar/a8efaf71cbe05928.jpg'/><img title='Почетный бейдж за поддержку Codeforces на его 10-летие' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/spookywooky" title="Specialist spookywooky" class="rated-user user-cyan">spookywooky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807251" href="?#comment-807251" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807251" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="872585" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807251"> <div class="moveup"> <div class="ttypography"><p>Explanation to E sounds like it would be possible to explain it in an understandable way.</p></div> </div> </div> <div class="reply info"> <a class="comment-807251 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807251 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807251"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807258" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807258" href="?#comment-807258" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807258" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807258"> <div class="moveup"> <div class="ttypography"><p><strong>If there is an item which costs 1, then we will not make the answer worse by buying this item.</strong></p><p>Why is that? For example, consider a situation where we've already bought all items, except for one, and it costs 2, and to make it cost 1 we need to buy 2 more items. In that case it would be cheaper to buy one left item and spend 2 instead of buing two more random items at cost 1 and finally buing one last item, spending 3 in total.</p></div> </div> </div> <div class="reply info"> <a class="comment-807258 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807258 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807258"> <li> <div class="comment"> <table class="comment-table" commentId="807275" commentParentId="807258"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807275" href="?#comment-807275" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807258" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807275" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807275"> <div class="moveup"> <div class="ttypography"><p>In your example you are explicitly making the cost of that item by buying more products of other items. But the statement means that if by buying other items and within limits i.e. less that $$$a_i$$$, then you should buy the items of cost 1.</p></div> </div> </div> <div class="reply info"> <a class="comment-807275 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807275 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807275"> <li> <div class="comment"> <table class="comment-table" commentId="807277" commentParentId="807275"> <tr> <td class="left"> <div style="position: absolute; left: 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/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:54">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807277" href="?#comment-807277" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807277" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807277"> <div class="moveup"> <div class="ttypography"><p>Thanks, that explains it:)</p></div> </div> </div> <div class="reply info"> <a class="comment-807277 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807277 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807277"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807331" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/NoobCpp" style="position: relative;"> <img src='https://userpic.codeforces.org/1716219/avatar/14a123abec8289d0.jpg'/> </a> <div><a href="/profile/NoobCpp" title="Specialist NoobCpp" class="rated-user user-cyan">NoobCpp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 17:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807331" href="?#comment-807331" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807331" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1716219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807331"> <div class="moveup"> <div class="ttypography"><p>Although E and F was more difficult than the rest, the contest was great. First time reach to Expert!!</p><p>Sr about my bad Eng :p</p></div> </div> </div> <div class="reply info"> <a class="comment-807331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807331"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807364" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/livlyf_168" style="position: relative;"> <img src='https://userpic.codeforces.org/1919608/avatar/cf064edf00e3eea6.jpg'/> </a> <div><a href="/profile/livlyf_168" title="Pupil livlyf_168" class="rated-user user-green">livlyf_168</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807364" href="?#comment-807364" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807364" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1919608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807364"> <div class="moveup"> <div class="ttypography"><p>Hey, can anyone help me with problem C. Don't know why is it giving WA on test 10. Below is my submission — <a href="/contest/1539/submission/120223010" title="Посылка 120223010 от livlyf_168">120223010</a>. I have used the same approach, except that I have taken The number of elements required to fill the gap as floor((d-1)/x). </p></div> </div> </div> <div class="reply info"> <a class="comment-807364 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807364 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807364"> <li> <div class="comment"> <table class="comment-table" commentId="807370" commentParentId="807364"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/itish" style="position: relative;"> <img src='https://userpic.codeforces.org/1589684/avatar/d4fea913edfbab4b.jpg'/> </a> <div><a href="/profile/itish" title="Candidate Master itish" class="rated-user user-violet">itish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807370" href="?#comment-807370" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807364" style="font-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="807370" 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="807370" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1589684" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807370"> <div class="moveup"> <div class="ttypography"><p>Change vector(int)split to vector(llint) split and it gets accepted</p></div> </div> </div> <div class="reply info"> <a class="comment-807370 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807370 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807370"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807374" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hotas" style="position: relative;"> <img src='https://userpic.codeforces.org/1150129/avatar/590cdb757ae4763a.jpg'/> </a> <div><a href="/profile/Hotas" title="Newbie Hotas" class="rated-user user-gray">Hotas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807374" href="?#comment-807374" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807374" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1150129" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807374"> <div class="moveup"> <div class="ttypography"><p>Can anyone tell me where am I doing wrong? I am getting wrong answer on test case 10. Problem C. Submission : <a href="/contest/1539/submission/120227942" title="Посылка 120227942 от Hotas">120227942</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807374 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807374 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807374"> <li> <div class="comment"> <table class="comment-table" commentId="807397" commentParentId="807374"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 20:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807397" href="?#comment-807397" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807374" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807397" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807397"> <div class="moveup"> <div class="ttypography"><p>I think the problem is that you have int[] a instead of ll[] a. Each element can be up to 1e18.</p></div> </div> </div> <div class="reply info"> <a class="comment-807397 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807397 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807397"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807378" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/coderaman327" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/coderaman327" title="Expert coderaman327" class="rated-user user-blue">coderaman327</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807378" href="?#comment-807378" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807378" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="886853" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807378"> <div class="moveup"> <div class="ttypography"><p>Can someone please tell me what my mistake is in problem D? <a href="https://codeforces.com/contest/1539/submission/120100696">My submission</a> Thanks in advance!!</p></div> </div> </div> <div class="reply info"> <a class="comment-807378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807378"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807400" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abyboi" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/abyboi" title="Pupil abyboi" class="rated-user user-green">abyboi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 21:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807400" href="?#comment-807400" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807400" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1833158" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807400"> <div class="moveup"> <div class="ttypography"><p>Can someone help me with Problem D? My submission is</p><p><a href="https://codeforces.com/contest/1539/submission/120232784">https://codeforces.com/contest/1539/submission/120232784</a></p><p>Thanks in advance!</p></div> </div> </div> <div class="reply info"> <a class="comment-807400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807400"> <li> <div class="comment"> <table class="comment-table" commentId="807478" commentParentId="807400"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/andr14142" style="position: relative;"> <img src='https://userpic.codeforces.org/620444/avatar/368d81a28bf4f89b.jpg'/> </a> <div><a href="/profile/andr14142" title="Pupil andr14142" class="rated-user user-green">andr14142</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 09:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807478" href="?#comment-807478" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807400" style="font-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="807478" 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="807478" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="620444" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807478"> <div class="moveup"> <div class="ttypography"><p>Your solution has not correct comparison in the case of whole buying goods without discount:<br /> else if (total_bought + products[j].F &lt; products[i].S)<br /> Correct comparison is:<br /> else if (total_bought + products[j].F &lt;= products[i].S)</p></div> </div> </div> <div class="reply info"> <a class="comment-807478 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807478 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807478"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807520" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Madara_Uzumaki" style="position: relative;"> <img src='https://userpic.codeforces.org/1621901/avatar/28eb09a48344e5fb.jpg'/> </a> <div><a href="/profile/Madara_Uzumaki" title="Newbie Madara_Uzumaki" class="rated-user user-gray">Madara_Uzumaki</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 11:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807520" href="?#comment-807520" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807520" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1621901" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807520"> <div class="moveup"> <div class="ttypography"><p>In <strong>problem</strong> C i ran the code in <strong>PyPy3</strong> the code got <strong>TLE in test case 18</strong> but when I ran the same code in <strong>Python3</strong> the code got <strong>accepted</strong> Can anyone clarify why did that happen?</p></div> </div> </div> <div class="reply info"> <a class="comment-807520 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807520 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807520"> <li> <div class="comment"> <table class="comment-table" commentId="807527" commentParentId="807520"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/casul" style="position: relative;"> <img src='https://userpic.codeforces.org/1690955/avatar/21ae0e21fe431dd7.jpg'/> </a> <div><a href="/profile/casul" title="Specialist casul" class="rated-user user-cyan">casul</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 12:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807527" href="?#comment-807527" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807520" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807527" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1690955" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807527"> <div class="moveup"> <div class="ttypography"><p>You may wanna check out this blog:</p><p><a href="https://codeforces.com/blog/entry/82989">https://codeforces.com/blog/entry/82989</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807527 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807527 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807527"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807629" commentParentId="807520"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aberent" 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/aberent" title="Specialist aberent" class="rated-user user-cyan">aberent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 18:13">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807629" href="?#comment-807629" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807520" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807629" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1157884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807629"> <div class="moveup"> <div class="ttypography"><p>I too got some strange behaviour with PyPy3 with test 18. Every version I tried printed a result and then (after it should have finished), got TLE. I wonder whether there is a bug somewhere here. See <a href="https://codeforces.com/blog/entry/92011">my blog entry</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-807629 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807629 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807629"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807566" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zvsevolod" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/zvsevolod" title="Newbie zvsevolod" class="rated-user user-gray">zvsevolod</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 14:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807566" href="?#comment-807566" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807566" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1271216" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807566"> <div class="moveup"> <div class="ttypography"><p>In problem C Java solution with Long[] array gets accepted, but long[] array solution gets TLE. (16th line in both solutions) </p><p>ACC: <a href="https://codeforces.com/contest/1539/submission/120284760">https://codeforces.com/contest/1539/submission/120284760</a> <br /> TLE: <a href="https://codeforces.com/contest/1539/submission/120284797">https://codeforces.com/contest/1539/submission/120284797</a></p><p>Could someone explain me why reference type works faster than primitive in this example?</p></div> </div> </div> <div class="reply info"> <a class="comment-807566 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807566 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807566"> <li> <div class="comment"> <table class="comment-table" commentId="807620" commentParentId="807566"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aberent" 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/aberent" title="Specialist aberent" class="rated-user user-cyan">aberent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 18:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807620" href="?#comment-807620" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807566" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807620" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1157884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807620"> <div class="moveup"> <div class="ttypography"><p>Apparently Java uses different sorting algorithms for integers (including longs) and objects. The algorithm for integers is generally faster, but its worst case is worse. You might have simply been unlucky. See the implementation notes for the two versions of sort: <a href="https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(long%5B%5D">https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(long%5B%5D</a>) <a href="https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(java.lang.Object%5B%5D">https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(java.lang.Object%5B%5D</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-807620 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807620 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807620"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807726" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/quinoa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/quinoa" title="Expert quinoa" class="rated-user user-blue">quinoa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 23:40">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807726" href="?#comment-807726" style="font-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="807726" 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="807726" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="592293" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807726"> <div class="moveup"> <div class="ttypography"><p>I had a hard time understanding the tutorial for problem E. This is my attempt at making it easier to understand.</p><p><strong>Easier problem: jump game</strong></p><p>Consider <a href="https://leetcode.com/problems/jump-game/">this</a> easier problem: you have an array $$$x$$$ where $$$x[i]$$$ means what the farthest is that you can jump from position $$$i$$$. Is it possible to reach the last element in the array if you start from position 0?</p><p>We can solve it with a DP where $$$dp[i]$$$ = can we reach the end if we start from position i? The solution to the problem is then equal to $$$dp[0]$$$. The transitions are like this: $$$dp[i]$$$ = $$$dp[i + 1]$$$ $$$||$$$ $$$dp[i + 2]$$$ $$$||$$$ ... $$$||$$$ $$$dp[i + x[i]]$$$. There are $$$N$$$ states and the transitions are $$$O(N)$$$ so this runs in $$$O(N^2)$$$.</p><p>We can make every transition $$$O(1)$$$ with a greedy insight. Instead of checking $$$dp[i + 1]$$$, ..., $$$dp[i + x[i]]$$$ we only need to check $$$dp[j]$$$ where $$$j$$$ is the leftmost position from which we can reach the end. The reason this works is that the leftmost position from which we can reach the end has the best probability of being within our jumping range. We can keep track of this leftmost position as we compute each state in a bottom up fashion.</p> <pre><code>int leftmost_possible = N - 1; for (int i = N - 2; i &gt;= 0; --i) { if (leftmost_possible &lt;= i + x[i]) { dp[i] = true; leftmost_possible = i; } } </code></pre><p><strong>Back to problem E</strong></p><p>We can again solve this with an $$$O(N^2)$$$ DP where $$$dp(x, y)$$$ = can we finish if card with index $$$x$$$ is in the left hand, and card with index $$$y$$$ is in the right hand (and we have just answered query $$$max(x, y)$$$). </p><p>We can notice that we can reduce the number of states to $$$N$$$. Because if we are at $$$dp(x, y)$$$ (WLOG $$$x &gt; y$$$) then</p> <ul> <li>either we will keep replacing the card in the left hand until we reach the end</li> <li>or at some point we have to take something in the right hand and we transition to state $$$dp(k, k + 1)$$$</li> </ul><p>So if we are at state (x, y) then in the next step either we are done, or we will transition to $$$dp(k, k + 1)$$$. Therefore (since we start at state $$$dp(0, 1)$$$) we will only visit states of the type $$$dp(k, k + 1)$$$ (and $$$dp(k - 1, k)$$$), and there are only $$$O(N)$$$ of those.</p><p>The transition is now $$$O(N)$$$ because we have to consider every $$$k$$$ such that $$$dp(k, k + 1)$$$ works. But with the same greedy insight as in the jump game problem we can reduce that to $$$O(1)$$$. Again we can store &quot;the leftmost k that works&quot; as we compute the states and therefore we can find the transition in $$$O(1)$$$.</p><p>Now of course in this problem another hard part is to compute the &quot;maximum jump length&quot; at every position. In the jump game problem this was given in the input, whereas here we have to compute it. For sure you can do it in logarithmic time with a segment tree (I saw it in <a href="https://www.youtube.com/watch?v=seaskdKf2sI">Colin Galen's video</a>). But apparently you can also do it in $$$O(1)$$$ since the solution runs in O(N) according to the tutorial. I didn't think about optimizing that part yet.</p></div> </div> </div> <div class="reply info"> <a class="comment-807726 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807726 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807726"> <li> <div class="comment"> <table class="comment-table" commentId="852194" commentParentId="807726"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ahshafi" style="position: relative;"> <img src='https://userpic.codeforces.org/818506/avatar/d65d006cfdce087a.jpg'/> </a> <div><a href="/profile/ahshafi" title="Candidate Master ahshafi" class="rated-user user-violet">ahshafi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/19/2021 17:24">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-852194" href="?#comment-852194" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807726" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="852194" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="818506" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-852194"> <div class="moveup"> <div class="ttypography"><p>me too confused about how to compute maximum jump length in O(1) </p></div> </div> </div> <div class="reply info"> <a class="comment-852194 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-852194 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-852194"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808157" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sg55" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sg55" title="Newbie sg55" class="rated-user user-gray">sg55</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/24/2021 05:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808157" href="?#comment-808157" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808157" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1445980" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808157"> <div class="moveup"> <div class="ttypography"><p>I have used 2 the same method as used by most of the other coders but my code is giving tle. Can please someone look and tell me why it is? <a href="/contest/1539/submission/120407076" title="Посылка 120407076 от sg55">120407076</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808157 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808157 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808157"> <li> <div class="comment"> <table class="comment-table" commentId="808253" commentParentId="808157"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zvsevolod" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/zvsevolod" title="Newbie zvsevolod" class="rated-user user-gray">zvsevolod</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/24/2021 13:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808253" href="?#comment-808253" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808157" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808253" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1271216" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808253"> <div class="moveup"> <div class="ttypography"><p>Try to use Long[] array instead of long[]. Also you may read my comment above.</p></div> </div> </div> <div class="reply info"> <a class="comment-808253 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808253 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808253"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hritik27" style="position: relative;"> <img src='https://userpic.codeforces.org/1232410/avatar/af014e1c10ef2a19.jpg'/> </a> <div><a href="/profile/hritik27" title="Newbie hritik27" class="rated-user user-gray">hritik27</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/24/2021 19:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808320" href="?#comment-808320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808320" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1232410" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808320"> <div class="moveup"> <div class="ttypography"><p>Can someone please help me with problem A?? Can't understand the solution give.</p></div> </div> </div> <div class="reply info"> <a class="comment-808320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808320"> <li> <div class="comment"> <table class="comment-table" commentId="810306" commentParentId="808320"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/songzy12" style="position: relative;"> <img src='https://userpic.codeforces.org/249570/avatar/3c83a5ef255ff4d6.jpg'/> </a> <div><a href="/profile/songzy12" title="Pupil songzy12" class="rated-user user-green">songzy12</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/30/2021 17:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810306" href="?#comment-810306" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808320" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810306" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="249570" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810306"> <div class="moveup"> <div class="ttypography"><p>1. First consider the case where there are infinite participants. Then each participant would be disturbed by $$$t/x$$$ participants following him. </p><p>2. Then consider the case that $$$n$$$ is finite but large enough, then the first participant would be disturbed by $$$t/x$$$, the same for participant 2, ..., until $$$k$$$. </p><p>For the participants beyond k, the number of participants that would disturb them are decreased by 1 each time, i.e., $$$t/x - 1$$$, $$$t/x - 2$$$, until 0 for the last participant.</p><p>There are $$$t/x$$$ numbers from $$$t/x - 1$$$ until 0, thus we know $$$k = n - t/x$$$.</p><p>So the answer would be $$$(n-t/x) * (t/x) + (t/x-1)*(t/x)/2$$$.</p><p>3. The $$$min$$$ and $$$max$$$ in the answer is to solve the case where n is not large enough, i.e., when $$$n &lt; t/x$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-810306 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810306 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810306"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808360" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/augurar" style="position: relative;"> <img src='https://userpic.codeforces.org/391071/avatar/8a814e47f9aacb44.jpg'/> </a> <div><a href="/profile/augurar" title="Expert augurar" class="rated-user user-blue">augurar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 02:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808360" href="?#comment-808360" style="font-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="808360" 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="808360" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="391071" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808360"> <div class="moveup"> <div class="ttypography"><p>I'm glad I didn't participate in this one officially. Problem C was easy but I kept getting a TLE for stupid language-specific reasons:</p> <ul> <li><p>My <a href="https://codeforces.com/contest/1539/submission/120478273">Python solution</a> got TLE on test 18 with PyPy3, but the same code passed with Python 3.</p></li> <li><p>My <a href="https://codeforces.com/contest/1539/submission/120478521">Java solution</a> got TLE on test 61, but passed if I changed <code>long[]</code> to <code>Long[]</code>. (This is kind of my fault for not knowing Java uses a worst-case O(n^2) sort for primitive arrays.)</p></li> <li><p>My <a href="https://codeforces.com/contest/1539/submission/120480356">C++ solution</a> passed with no special optimization.</p></li> </ul><p>In my opinion that's an indication that the time limit is overly strict, especially for an ABC problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-808360 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808360 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808360"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="816645" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/comseung18_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/comseung18_" title="Expert comseung18_" class="rated-user user-blue">comseung18_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/15/2021 09:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-816645" href="?#comment-816645" style="font-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="816645" 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="816645" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275870" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-816645"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1539/submission/122552751" title="Посылка 122552751 от comseung18_">122552751</a> why my solution A is not correct ? ans1 is Editorial solution ans2 is my solution</p><p>I checked my ans2 in many times. but ans1 equals ans2..<br />~~~~~ import random k = int(input()) for _ in range(k): n = random.randint(1,2*1000000000) x = random.randint(1,2*1000000000) t = random.randint(1,2*1000000000) tmp = t//x ans1 = max(0,n-tmp)*tmp + min(n-1,tmp-1)*min(n,tmp)//2 ans2 = tmp*n — tmp*tmp + tmp*n — ((2*n-tmp+1)*tmp)//2 if ans1 != ans2: print(ans1,ans2) ~~~~~</p></div> </div> </div> <div class="reply info"> <a class="comment-816645 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-816645 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-816645"> <li> <div class="comment"> <table class="comment-table" commentId="816647" commentParentId="816645"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/comseung18_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/comseung18_" title="Expert comseung18_" class="rated-user user-blue">comseung18_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/15/2021 09:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-816647" href="?#comment-816647" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-816645" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="816647" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275870" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-816647"> <div class="moveup"> <div class="ttypography"><p>when , t/x &gt; n , ans2 is wrong sorry</p></div> </div> </div> <div class="reply info"> <a class="comment-816647 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-816647 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-816647"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="984743" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PrickyToTheMoon" style="position: relative;"> <img src='https://userpic.codeforces.org/1432360/avatar/422cb9d88c769b8d.jpg'/> </a> <div><a href="/profile/PrickyToTheMoon" title="Pupil PrickyToTheMoon" class="rated-user user-green">PrickyToTheMoon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/24/2022 21:10">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-984743" href="?#comment-984743" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="984743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1432360" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-984743"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1539/submission/186604051" title="Submission 186604051 by PrickyToTheMoon">186604051</a></p><p>Please help. Cannot understand why getting WA on test case 18. My approach matches perfectly with editorial.</p><p>Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-984743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-984743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-984743"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="995447" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mohsina_Shaikh" style="position: relative;"> <img src='https://userpic.codeforces.org/1396580/avatar/6f21616a2d8d578.jpg'/> </a> <div><a href="/profile/Mohsina_Shaikh" title="Newbie Mohsina_Shaikh" class="rated-user user-gray">Mohsina_Shaikh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/25/2023 07:37">8 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-995447" href="?#comment-995447" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="995447" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1396580" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-995447"> <div class="moveup"> <div class="ttypography"><p>can anyone please explain how problem B can be solved using DP.</p></div> </div> </div> <div class="reply info"> <a class="comment-995447 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-995447 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-995447"> </ul> </div> <br/> <div id="editBox-100475" 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 firstPreview100475 = true; var lastPreviewContent100475 = ''; 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=100475] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=100475] 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-92516").click(function () { $.post("/data/topic/vote", {topicId: 92516, _tta: Codeforces.tta(), topicRevisionId: 229854, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-92516").click(function () { $.post("/data/topic/vote", {topicId: 92516, _tta: Codeforces.tta(), topicRevisionId: 229854, 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:33:26</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:'81289365b9230c42',t:'MTY5NjcwNzIwNi44NDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1539B
1539
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>Однажды Петя в очередной раз написал грустную песню про любовь и поспешил показать ее Васе. Песня представляет собой строку из маленьких букв английского алфавита. У Васи сразу возникло $$$q$$$ вопросов про эту песню. Каждый вопрос представляет собой некоторый отрезок песни с позиции $$$l$$$ до позиции $$$r$$$. Вася рассматривает подстроку, образованную символами на этом отрезке, а затем повторяет каждую букву в этой подстроке $$$k$$$ раз, где $$$k$$$ — порядковый номер буквы в алфавите. Например, если Вася выбрал подстроку «<span class="tex-font-style-tt">abbcb</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>» — три раза, и полученная строка будет равна «<span class="tex-font-style-tt">abbbbcccbb</span>», ее длина равна $$$10$$$. Вася интересуется именно длиной полученной строки.</p><p>Помогите Пете ответить Васе на его вопросы, а именно, для каждого из заданных вопросов определите длину строки, которую выпишет Вася.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке вводятся числа $$$n$$$ и $$$q$$$ ($$$1\leq n\leq 100\,000$$$, $$$1\leq q \leq 100\,000$$$) — длина песни и количество вопросов. </p><p>Во второй строке дана строка $$$s$$$ — сама песня, представляющая собой строку длины $$$n$$$ из маленьких букв английского алфавита.</p><p>В следующих $$$q$$$ строках даны описания вопросов. Каждое описание состоит из двух чисел $$$l$$$ и $$$r$$$ ($$$1 \leq l \leq r \leq n$$$) — границы каждого из вопросов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ строк — для каждого вопроса выведите длину строки, которую выпишет Вася.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 3 abacaba 1 3 2 5 1 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 7 11 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 4 abbabaa 1 3 5 7 6 6 2 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 4 1 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 13 7 sonoshikumiwo 1 5 2 10 7 7 1 13 4 8 2 5 3 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 82 125 9 191 62 63 97 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере Васю интересуют три вопроса. В первом вопросе Вася рассматривает подстроку «<span class="tex-font-style-tt">aba</span>», которая превратится в «<span class="tex-font-style-tt">abba</span>», а значит, ответ на этот вопрос равен $$$4$$$. Во втором вопросе Вася рассматривает подстроку «<span class="tex-font-style-tt">baca</span>», которая превратится в «<span class="tex-font-style-tt">bbaccca</span>», а значит, ответ на этот вопрос будет равен $$$7$$$. В третьем вопросе Вася рассматривает всю строку «<span class="tex-font-style-tt">abacaba</span>», которая превратится в «<span class="tex-font-style-tt">abbacccabba</span>» — строку длины $$$11$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="39feb6d7664fd75ca7faffe8db49ad8f"/> <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="3b3d6aa18ec7f2c8636f747ba32c1b3c7997564d"/> <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='39feb6d7664fd75ca7faffe8db49ad8f'>&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%2F1539%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='39feb6d7664fd75ca7faffe8db49ad8f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1539">Codeforces Round 727 (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='39feb6d7664fd75ca7faffe8db49ad8f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1539/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='39feb6d7664fd75ca7faffe8db49ad8f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1021671"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='39feb6d7664fd75ca7faffe8db49ad8f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1021671"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91905" title="Codeforces Round #727 (Div. 2, по Всероссийской олимпиаде имени Келдыша) [Рейтинговый]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13910:13911" 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/91906" title="tutorial" target="_blank">tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13923" 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/1539">Задачи</a></li> <li><a href="/contest/1539/submit">Отослать</a></li> <li><a href="/contest/1539/my">Мои посылки</a></li> <li><a href="/contest/1539/status">Статус</a></li> <li><a href="/contest/1539/hacks">Взломы</a></li> <li><a href="/contest/1539/room/1">Комната</a></li> <li><a href="/contest/1539/standings">Положение</a></li> <li><a href="/contest/1539/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_4f58a3dda0299e0d0ff80d8d1c8fc177fe350467"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Однажды Петя в очередной раз написал грустную песню про любовь и поспешил показать ее Васе. Песня представляет собой строку из маленьких букв английского алфавита. У Васи сразу возникло $$$q$$$ вопросов про эту песню. Каждый вопрос представляет собой некоторый отрезок песни с позиции $$$l$$$ до позиции $$$r$$$. Вася рассматривает подстроку, образованную символами на этом отрезке, а затем повторяет каждую букву в этой подстроке $$$k$$$ раз, где $$$k$$$ — порядковый номер буквы в алфавите. Например, если Вася выбрал подстроку «<span class="tex-font-style-tt">abbcb</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>» — три раза, и полученная строка будет равна «<span class="tex-font-style-tt">abbbbcccbb</span>», ее длина равна $$$10$$$. Вася интересуется именно длиной полученной строки.</p><p>Помогите Пете ответить Васе на его вопросы, а именно, для каждого из заданных вопросов определите длину строки, которую выпишет Вася.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке вводятся числа $$$n$$$ и $$$q$$$ ($$$1\leq n\leq 100\,000$$$, $$$1\leq q \leq 100\,000$$$) — длина песни и количество вопросов. </p><p>Во второй строке дана строка $$$s$$$ — сама песня, представляющая собой строку длины $$$n$$$ из маленьких букв английского алфавита.</p><p>В следующих $$$q$$$ строках даны описания вопросов. Каждое описание состоит из двух чисел $$$l$$$ и $$$r$$$ ($$$1 \leq l \leq r \leq n$$$) — границы каждого из вопросов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ строк — для каждого вопроса выведите длину строки, которую выпишет Вася.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 3 abacaba 1 3 2 5 1 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 7 11 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 4 abbabaa 1 3 5 7 6 6 2 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 4 1 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 13 7 sonoshikumiwo 1 5 2 10 7 7 1 13 4 8 2 5 3 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 82 125 9 191 62 63 97 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере Васю интересуют три вопроса. В первом вопросе Вася рассматривает подстроку «<span class="tex-font-style-tt">aba</span>», которая превратится в «<span class="tex-font-style-tt">abba</span>», а значит, ответ на этот вопрос равен $$$4$$$. Во втором вопросе Вася рассматривает подстроку «<span class="tex-font-style-tt">baca</span>», которая превратится в «<span class="tex-font-style-tt">bbaccca</span>», а значит, ответ на этот вопрос будет равен $$$7$$$. В третьем вопросе Вася рассматривает всю строку «<span class="tex-font-style-tt">abacaba</span>», которая превратится в «<span class="tex-font-style-tt">abbacccabba</span>» — строку длины $$$11$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c694c8622de5',t:'MTY5NjY2NzM1OS41NzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u043e\u043a\u0438", "*800"]
https://codeforces.com/blog/entry/91906
<!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="c4ae3f1dbdd3aa7685e27f571fc144d8"/> <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="Codeforces Round #727 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #727 Editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='c4ae3f1dbdd3aa7685e27f571fc144d8'>&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%2F91906">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='c4ae3f1dbdd3aa7685e27f571fc144d8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:31:34</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:31:34</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='c4ae3f1dbdd3aa7685e27f571fc144d8'/> <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="92516"> <div class="title"> <a href="/blog/entry/91906"> <p>Codeforces Round #727 Editorial</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="Jun/18/2021 00:11">2 years ago</span>, translation, <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/1539/problem/A" title="Codeforces Round 727 (Div. 2)">1539A - Contest Start</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/1539/problem/B" title="Codeforces Round 727 (Div. 2)">1539B - Love Song</a> was authored by jury and prepared by <a class="rated-user user-red" href="/profile/talant" title="Grandmaster talant">talant</a></p><p><a href="/contest/1539/problem/C" title="Codeforces Round 727 (Div. 2)">1539C - Stable Groups</a> was authored by <a class="rated-user user-orange" href="/profile/Artyom123" title="International Master Artyom123">Artyom123</a> and prepared by <a class="rated-user user-orange" href="/profile/Artyom123" title="International Master Artyom123">Artyom123</a> and <a class="rated-user user-blue" href="/profile/shishyando" title="Expert shishyando">shishyando</a></p><p><a href="/contest/1539/problem/D" title="Codeforces Round 727 (Div. 2)">1539D - PriceFixed</a> was authored by Helen Andreeva and prepared by <a class="rated-user user-red" href="/profile/Siberian" title="Grandmaster Siberian">Siberian</a></p><p><a href="/contest/1539/problem/E" title="Codeforces Round 727 (Div. 2)">1539E - Game with Cards</a> was authored and prepared by <a class="rated-user user-orange" href="/profile/TeaTime" title="Master TeaTime">TeaTime</a></p><p><a href="/contest/1539/problem/F" title="Codeforces Round 727 (Div. 2)">1539F - Strange Array</a> was authored and prepared by <a class="rated-user user-orange" href="/profile/Tikhon228" title="Master Tikhon228">Tikhon228</a></p> <div class="problemTutorial" problemcode="1539A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539C">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539D">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539E">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539F">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/1539" class="notice" style="text-decoration: none;">Codeforces Round 727 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-42191-92516").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: "91906", 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> <span style="padding: 0 0.35em;"> <a href="/search?query=%23727" class="tag notice" style="text-decoration: none;">#727</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-92516"><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'>+79</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-92516"><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="Jun/18/2021 00:11">2 years ago</span> </li> <li> <a href="/blog/entry/91906#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/91906#comments"> 116 </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="100475"> <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 (81)</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="807107" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hhoppitree" style="position: relative;"> <img src='https://userpic.codeforces.org/1366950/avatar/874468310bfb5ee5.jpg'/> </a> <div><a href="/profile/hhoppitree" title="Grandmaster hhoppitree" class="rated-user user-red">hhoppitree</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 01:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807107" href="?#comment-807107" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807107" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1366950" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807107"> <div class="moveup"> <div class="ttypography"><p>A great competition with hacking :)</p></div> </div> </div> <div class="reply info"> <a class="comment-807107 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807107 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807107"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807116" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iLoveIOI" style="position: relative;"> <img src='https://userpic.codeforces.org/483613/avatar/19b4d34a35f1e022.jpg'/> </a> <div><a href="/profile/iLoveIOI" title="Master iLoveIOI" class="rated-user user-orange">iLoveIOI</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 03:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807116" href="?#comment-807116" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807116" class="CommentVoteFrame" data-commentRating="34" data-commentUserId="483613" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+34</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807116"> <div class="moveup"> <div class="ttypography"><p>Can someone explain one of the multiset solutions to E? Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-807116 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807116 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807116"> <li> <div class="comment"> <table class="comment-table" commentId="807421" commentParentId="807116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lazywitt" style="position: relative;"> <img src='https://userpic.codeforces.org/995139/avatar/e4276e734c1b167e.jpg'/> </a> <div><a href="/profile/lazywitt" title="Pupil lazywitt" class="rated-user user-green">lazywitt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 21:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807421" href="?#comment-807421" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807116" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807421" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="995139" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807421"> <div class="moveup"> <div class="ttypography"><p>Can you show any multiset solutions which passed ? </p></div> </div> </div> <div class="reply info"> <a class="comment-807421 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807421 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807421"> <li> <div class="comment"> <table class="comment-table" commentId="807448" commentParentId="807421"> <tr> <td class="left"> <div style="position: absolute; left: 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/iLoveIOI" style="position: relative;"> <img src='https://userpic.codeforces.org/483613/avatar/19b4d34a35f1e022.jpg'/> </a> <div><a href="/profile/iLoveIOI" title="Master iLoveIOI" class="rated-user user-orange">iLoveIOI</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 04:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807448" href="?#comment-807448" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807421" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807448" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="483613" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807448"> <div class="moveup"> <div class="ttypography"><p>For example, <a href="https://codeforces.com/contest/1539/submission/120110352">this</a> and <a href="https://codeforces.com/contest/1539/submission/120092916">this</a>. </p></div> </div> </div> <div class="reply info"> <a class="comment-807448 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807448 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807448"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807484" commentParentId="807116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lucaperju" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lucaperju" title="International Grandmaster lucaperju" class="rated-user user-red">lucaperju</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 09:45">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807484" href="?#comment-807484" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807116" style="font-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="807484" 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="807484" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="627011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807484"> <div class="moveup"> <div class="ttypography"><p>Consider dpL[i][j] (different from the one from the editorial) as equal to 1 if it's possible to take the first i cards, ith one in the left hand, and j being the last card we took in the right hand (j&lt;i). And, dpR[j][i] as equal to 1 if it's possible to take the first i cards, last one in the right hand, and j being the last card we took in the left hand. then, instead of storing the whole array, let L[i] be a set (or multiset) of pairs of &lt;k[j],j&gt; such that dpL[i][j] is 1, (and the same for R[i]). Now, if we're at step i and know L[i] and R[i], let's try to compute L[i+1] and R[i+1]: Let's focus on computing L[i+1], for R[i+1] it's similar: if (i+1)th card can't go in the left hand, then L[i+1] will be empty, let's assume it can go there. Let's also assume that the (i+1)th right hand can take any card, we'll fix that later. Then, first of all, if the set R[i] is not empty, we should add the pair &lt;k[i],i&gt; to L[i+1], that's because we can go from having the cards from (j, i) to (i+1, i) by taking the i+1th card in the left hand. And, let's also add to L[i+1] all the pairs from L[i], because we can get those by going from (i, j) to (i+1, j). Now, I assumed that the (i+1)th right hand can take any card, while in reality it can only take those whose k is between ar[i+1] and br[i+1]. So, let's erase from L[i+1] the pairs that are not valid. Since it's a set, we can just erase the smallest card values and the highest card values from the set which are not in the interval. This might seem like it's too slow, but it's actually amortized, because at each step, we only add at most one new pair to the set ( the pair &lt;k[i], i&gt; ), and delete some of the pairs which aren't valid. I'm not sure if I explained this very well, I hope it's clear.</p></div> </div> </div> <div class="reply info"> <a class="comment-807484 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807484 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807484"> <li> <div class="comment"> <table class="comment-table" commentId="807490" commentParentId="807484"> <tr> <td class="left"> <div style="position: absolute; left: 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/iLoveIOI" style="position: relative;"> <img src='https://userpic.codeforces.org/483613/avatar/19b4d34a35f1e022.jpg'/> </a> <div><a href="/profile/iLoveIOI" title="Master iLoveIOI" class="rated-user user-orange">iLoveIOI</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 10:26">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807490" href="?#comment-807490" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807484" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807490" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="483613" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807490"> <div class="moveup"> <div class="ttypography"><p>Ah, I see thanks a lot! It was very clear :)</p></div> </div> </div> <div class="reply info"> <a class="comment-807490 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807490 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807490"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807916" commentParentId="807484"> <tr> <td class="left"> <div style="position: absolute; left: 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/Mrajaryan" style="position: relative;"> <img src='https://userpic.codeforces.org/1377953/avatar/e904b3a3a2eac1ad.jpg'/> </a> <div><a href="/profile/Mrajaryan" title="Newbie Mrajaryan" class="rated-user user-gray">Mrajaryan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 13:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807916" href="?#comment-807916" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807484" style="font-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="807916" 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="807916" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1377953" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807916"> <div class="moveup"> <div class="ttypography"><p>Thanks for explanation. But I can't understand why I should use dp? Can you please give some idea on this ? Or just tell me the naive approach by which i can solve the problem? Like naive dp approach</p></div> </div> </div> <div class="reply info"> <a class="comment-807916 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807916 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807916"> <li> <div class="comment"> <table class="comment-table" commentId="807995" commentParentId="807916"> <tr> <td class="left"> <div style="position: absolute; left: 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/lucaperju" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lucaperju" title="International Grandmaster lucaperju" class="rated-user user-red">lucaperju</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 17:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807995" href="?#comment-807995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807916" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807995" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="627011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807995"> <div class="moveup"> <div class="ttypography"><p>A naive dp approach using the same dp I described above would be: dpL[i][j] (j&lt;i) is true if, obviously, ith card can stay in the left hand (at step i), and jth card can stay in the right hand (at step i), and either:</p> <ul> <li><p>j &lt; (i-1), and dpL[i-1][j] is true</p></li> <li><p>OR j == (i-1), and there exists such k &lt; (i-1) so that dpR[k][i-1] is true</p></li> </ul><p>And similarly for dpR. After calculating this, you can easily recreate the solution from right to left.</p></div> </div> </div> <div class="reply info"> <a class="comment-807995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807995"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="810899" commentParentId="807484"> <tr> <td class="left"> <div style="position: absolute; left: 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/vishaaaal" style="position: relative;"> <img src='https://userpic.codeforces.org/1443354/avatar/25a2dd924894eeeb.jpg'/> </a> <div><a href="/profile/vishaaaal" title="Expert vishaaaal" class="rated-user user-blue">vishaaaal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/02/2021 20:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810899" href="?#comment-810899" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807484" style="font-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="810899" 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="810899" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1443354" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-810899"> <div class="moveup"> <div class="ttypography"><p>How will the following be represented according to these dp states?</p><p>We can pick all the cards upto the ith card in the left hand but none of them in the right hand (in other words, all the queries are answered on the left hand upto the ith card). </p><p>This would imply that there is no j such that dpL[i][j] is 1. But still we can answer all the queries upto the ith card.</p><p>Edit: I thought a lil bit about it and I think we can use 0 as a dummy card (which basically means, by default we'll have 0 as a card in right hand if we don't pick any card in it). And yess, AC. Great explanation OFZ.</p></div> </div> </div> <div class="reply info"> <a class="comment-810899 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810899 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810899"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807117" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Acfboy" style="position: relative;"> <img src='https://userpic.codeforces.org/873793/avatar/146c53315bccb6e9.jpg'/> </a> <div><a href="/profile/Acfboy" title="Master Acfboy" class="rated-user user-orange">Acfboy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 03:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807117" href="?#comment-807117" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807117" class="CommentVoteFrame" data-commentRating="61" data-commentUserId="873793" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+61</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807117"> <div class="moveup"> <div class="ttypography"><p>Nice problems, but the gap between problem ABCD and EF seems too large.</p></div> </div> </div> <div class="reply info"> <a class="comment-807117 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807117 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807117"> <li> <div class="comment"> <table class="comment-table" commentId="807121" commentParentId="807117"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807121" href="?#comment-807121" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807117" style="font-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="807121" 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="807121" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807121"> <div class="moveup"> <div class="ttypography"><p>I think there is a mistake in the editorial of the Problem F.</p><p>The editorial said if the $$$a_i$$$ is less than or equal to the median element then $$$ans = \left\lfloor\dfrac{cnt_R+cnt_M-cnt_L+1}{2} \right\rfloor$$$, but if I have an array that is $$$[1, 2, 3, 4, 4, 6]$$$, the ans of the number $$$4$$$ should be 1, and if you use the formula mentioned above, you may get a wrong answer 0.</p><p>Could anyone tell me the correct formula?</p></div> </div> </div> <div class="reply info"> <a class="comment-807121 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807121 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807121"> <li> <div class="comment"> <table class="comment-table" commentId="807156" commentParentId="807121"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807156" href="?#comment-807156" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807121" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807156" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807156"> <div class="moveup"> <div class="ttypography"><p>The formula is correct, but it's for when the element come to the left of median. When element comes to right of median, other formula should be used which should give you 1. That's why we should take maximum from left &amp; right.</p></div> </div> </div> <div class="reply info"> <a class="comment-807156 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807156 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807156"> <li> <div class="comment"> <table class="comment-table" commentId="807196" commentParentId="807156"> <tr> <td class="left"> <div style="position: absolute; left: 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/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807196" href="?#comment-807196" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807156" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807196" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807196"> <div class="moveup"> <div class="ttypography"><p>Thank you very much. You're right and I have solved this problem by using two distinct formulas. </p></div> </div> </div> <div class="reply info"> <a class="comment-807196 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807196 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807196"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807159" commentParentId="807121"> <tr> <td class="left"> <div style="position: absolute; left: 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/Ka1hatsu" style="position: relative;"> <img src='https://userpic.codeforces.org/761494/avatar/5d5b8ffd577a29a8.jpg'/> </a> <div><a href="/profile/Ka1hatsu" title="Pupil Ka1hatsu" class="rated-user user-green">Ka1hatsu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807159" href="?#comment-807159" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807121" style="font-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="807159" 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="807159" class="CommentVoteFrame" data-commentRating="-6" data-commentUserId="761494" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807159"> <div class="moveup"> <div class="ttypography"><p>sorry</p></div> </div> </div> <div class="reply info"> <a class="comment-807159 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807159 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807159"> <li> <div class="comment"> <table class="comment-table" commentId="807192" commentParentId="807159"> <tr> <td class="left"> <div style="position: absolute; left: 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/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807192" href="?#comment-807192" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807159" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807192" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807192"> <div class="moveup"> <div class="ttypography"><p>I'm sorry but the median number is 4 according to the Problem F.</p></div> </div> </div> <div class="reply info"> <a class="comment-807192 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807192 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807192"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807120" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/highighiq" style="position: relative;"> <img src='https://userpic.codeforces.org/1420719/avatar/97be0e366e499727.jpg'/> </a> <div><a href="/profile/highighiq" title="Master highighiq" class="rated-user user-orange">highighiq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807120" href="?#comment-807120" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807120" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="1420719" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807120"> <div class="moveup"> <div class="ttypography"><p>Good problems!(But E,F is too difficult!) And I get to expert!</p></div> </div> </div> <div class="reply info"> <a class="comment-807120 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807120 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807120"> <li> <div class="comment"> <table class="comment-table" commentId="807122" commentParentId="807120"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807122" href="?#comment-807122" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807120" style="font-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="807122" 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="807122" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807122"> <div class="moveup"> <div class="ttypography"><p>Congratulations!</p></div> </div> </div> <div class="reply info"> <a class="comment-807122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807122"> <li> <div class="comment"> <table class="comment-table" commentId="807125" commentParentId="807122"> <tr> <td class="left"> <div style="position: absolute; left: 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/highighiq" style="position: relative;"> <img src='https://userpic.codeforces.org/1420719/avatar/97be0e366e499727.jpg'/> </a> <div><a href="/profile/highighiq" title="Master highighiq" class="rated-user user-orange">highighiq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:12">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807125" href="?#comment-807125" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807122" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807125" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1420719" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807125"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-807125 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807125 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807125"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807124" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hithu" style="position: relative;"> <img src='https://userpic.codeforces.org/202138/avatar/c537257b9e17f402.jpg'/> </a> <div><a href="/profile/hithu" title="Pupil hithu" class="rated-user user-green">hithu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:09">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807124" href="?#comment-807124" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="202138" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807124"> <div class="moveup"> <div class="ttypography"><p>Still don't understand editorial of D, can anybody explain the two pointer technique?</p></div> </div> </div> <div class="reply info"> <a class="comment-807124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807124"> <li> <div class="comment"> <table class="comment-table" commentId="807128" commentParentId="807124"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Enigma20" style="position: relative;"> <img src='https://userpic.codeforces.org/1301418/avatar/3ba73a2cb1eeb8ef.jpg'/> </a> <div><a href="/profile/Enigma20" title="Expert Enigma20" class="rated-user user-blue">Enigma20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807128" href="?#comment-807128" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807124" style="font-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="807128" 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="807128" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="1301418" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807128"> <div class="moveup"> <div class="ttypography"><p>First we sort the array according to increasing order of $$$b_i$$$. Now, we maintain 2 pointers one at the start of the array(say $$$i$$$) and other one at the end(say $$$j$$$). Also, let's maintain two variables $$$cur$$$(stores number of products already taken), $$$ans$$$(stores the required answer).</p><p>Now, we run a loop until $$$i\leq j$$$.</p><p>If $$$cur\geq b_i$$$, there is no point to leave this product, so we buy all $$$a_i$$$ products with 50% discount and update our $$$cur$$$ and $$$ans$$$.</p><p>If $$$cur\lt b_i$$$, then we start from second pointer i.e. $$$j$$$ and keep taking $$$min(b_i-cur,a_j)$$$ products for 2 rubles, if $$$cur\lt b_j$$$, otherwise for 1 ruble. We stop once we have $$$cur\geq b_i$$$. Update $$$cur,ans,a_j$$$ accordingly. If $$$a_j=0$$$, decrement $$$j$$$.</p><p><a href="https://codeforces.com/contest/1539/submission/120108298">My submission</a></p><p>In this submission, I ran a loop until $$$i\lt j$$$ and checked $$$i=j$$$ condition separately but that isn't necessary.</p></div> </div> </div> <div class="reply info"> <a class="comment-807128 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807128 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807128"> <li> <div class="comment"> <table class="comment-table" commentId="807155" commentParentId="807128"> <tr> <td class="left"> <div style="position: absolute; left: 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/crozzhtt" style="position: relative;"> <img src='https://userpic.codeforces.org/1592985/avatar/ea9a2bfb02b015fb.jpg'/> </a> <div><a href="/profile/crozzhtt" title="Newbie crozzhtt" class="rated-user user-gray">crozzhtt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807155" href="?#comment-807155" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807128" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807155" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1592985" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807155"> <div class="moveup"> <div class="ttypography"><p>but when cur &lt; bi I wonder if I can choose to continue buying (i-1)th product for 1 ruble or buying j-th product for 2 rubles. Will the 2nd option be more optimal than the 1st option?</p></div> </div> </div> <div class="reply info"> <a class="comment-807155 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807155 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807155"> <li> <div class="comment"> <table class="comment-table" commentId="807161" commentParentId="807155"> <tr> <td class="left"> <div style="position: absolute; left: 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/Enigma20" style="position: relative;"> <img src='https://userpic.codeforces.org/1301418/avatar/3ba73a2cb1eeb8ef.jpg'/> </a> <div><a href="/profile/Enigma20" title="Expert Enigma20" class="rated-user user-blue">Enigma20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807161" href="?#comment-807161" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807155" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807161" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1301418" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807161"> <div class="moveup"> <div class="ttypography"><p>Yes, second case will be optimal. Look at it this way, you have to buy as many products for 50% discount as possible. Now we know $$$i^{th}$$$ product has smaller $$$b_i$$$, so the condition for discount of this product will be fulfilled by taking lesser number of products for 2 rubles. Also it may happen that after taking $$$i^{th}$$$ product for 50% discount, products with higher $$$b_i$$$ can be taken for 50% discount without additional cost of 2 rubles. So, 2nd case will be optimal.</p></div> </div> </div> <div class="reply info"> <a class="comment-807161 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807161 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807161"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807130" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/avdp" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/avdp" title="Newbie avdp" class="rated-user user-gray">avdp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807130" href="?#comment-807130" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807130" class="CommentVoteFrame" data-commentRating="97" data-commentUserId="1840186" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+97</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807130"> <div class="moveup"> <div class="ttypography"><p><img alt=" " src="/predownloaded/0d/c4/0dc4ee86562ac0c8d31bcf482bed113f62f1fda1.jpg" style="max-width: 100.0%;max-height: 100.0%;" /></p><p><a class="rated-user user-red" href="/profile/galen_colin" title="Международный гроссмейстер galen_colin">galen_colin</a> <strong>too</strong></p></div> </div> </div> <div class="reply info"> <a class="comment-807130 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807130 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807130"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807132" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Atomsky" style="position: relative;"> <img src='https://userpic.codeforces.org/336914/avatar/2c5685b756a63503.jpg'/> </a> <div><a href="/profile/Atomsky" title="Newbie Atomsky" class="rated-user user-gray">Atomsky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807132" href="?#comment-807132" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807132" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="336914" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807132"> <div class="moveup"> <div class="ttypography"><p>I submitted <a href="/contest/1539/submission/120147862" title="Посылка 120147862 от Atomsky">120147862</a> for Problem-C. It gave a wrong result on test 62 in GNU C++17. When I submitted the same code in C++11, it was accepted (<a href="/contest/1539/submission/120149347" title="Посылка 120149347 от Atomsky">120149347</a>).</p><p>It would be helpful if anyone tells me what went wrong in my code.</p></div> </div> </div> <div class="reply info"> <a class="comment-807132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807132"> <li> <div class="comment"> <table class="comment-table" commentId="807136" commentParentId="807132"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/avdp" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/avdp" title="Newbie avdp" class="rated-user user-gray">avdp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 06:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807136" href="?#comment-807136" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807136" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1840186" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807136"> <div class="moveup"> <div class="ttypography"><p>Hey there, It is because of precision error differences in C++11 and C++17, So it is always advised to use <strong>long double</strong> instead of <strong>double</strong>. You will get AC in both versions with <strong>long double</strong>.</p></div> </div> </div> <div class="reply info"> <a class="comment-807136 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807136 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807136"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807165" commentParentId="807132"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/maskman_lucifer" style="position: relative;"> <img src='https://userpic.codeforces.org/1453975/avatar/e7e8769e223b3ab9.jpg'/> </a> <div><a href="/profile/maskman_lucifer" title="Pupil maskman_lucifer" class="rated-user user-green">maskman_lucifer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807165" href="?#comment-807165" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807165" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1453975" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807165"> <div class="moveup"> <div class="ttypography"><p>In these cases use this (val + d-1 )/ d instead of some ceil on double (Try to avoid doubles if you can do the same with int (precision issue)).<br /> In your case foo[i] = (jar[i] — jar[i-1] + x-1)/x will be good to go.</p></div> </div> </div> <div class="reply info"> <a class="comment-807165 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807165 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807165"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807144" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/UpMing" style="position: relative;"> <img src='https://userpic.codeforces.org/1424136/avatar/2e9bc60a07619853.jpg'/> </a> <div><a href="/profile/UpMing" title="Candidate Master UpMing" class="rated-user user-violet">UpMing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 06:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807144" href="?#comment-807144" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807144" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="1424136" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807144"> <div class="moveup"> <div class="ttypography"><p>The difficulty range is very large,</p><p>For example, D through E</p></div> </div> </div> <div class="reply info"> <a class="comment-807144 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807144 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807144"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807157" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hurt_FOR_heart" style="position: relative;"> <img src='https://userpic.codeforces.org/1445761/avatar/4bd86d3c8cfb747a.jpg'/> </a> <div><a href="/profile/hurt_FOR_heart" title="Candidate Master hurt_FOR_heart" class="rated-user user-violet">hurt_FOR_heart</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807157" href="?#comment-807157" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807157" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="1445761" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807157"> <div class="moveup"> <div class="ttypography"><p>In problem E, i thing that it's hard to come up with such dp state. Does anyone have a more natural idea for this problem ? </p></div> </div> </div> <div class="reply info"> <a class="comment-807157 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807157 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807157"> <li> <div class="comment"> <table class="comment-table" commentId="807183" commentParentId="807157"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/andr14142" style="position: relative;"> <img src='https://userpic.codeforces.org/620444/avatar/368d81a28bf4f89b.jpg'/> </a> <div><a href="/profile/andr14142" title="Pupil andr14142" class="rated-user user-green">andr14142</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 08:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807183" href="?#comment-807183" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807157" style="font-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="807183" revisionCount="7" revision="7"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">7</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="807183" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="620444" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807183"> <div class="moveup"> <div class="ttypography"><p>A more natural idea is to calculate limits for both hands from the end.<br /> Last move has no limits. The range for both hands of last move is from 0 to m inclusive.<br /> For the previous move check cases. Initially limits impossible m &lt; k &lt; 0.<br /> If you can take the card into left hand, then check, could you keep your right hand for the next move? If left card may be kept, limits for the right hand are the current limits for right hand. Otherwise right hand must be kept for the next move, so intersect current limits for right hand with limits for next move.<br /> The same for the right hand.<br /> Finally we check limits for initial situation, is pair (0,0) allowed.</p></div> </div> </div> <div class="reply info"> <a class="comment-807183 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807183 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807183"> <li> <div class="comment"> <table class="comment-table" commentId="807186" commentParentId="807183"> <tr> <td class="left"> <div style="position: absolute; left: 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/rag-hav" style="position: relative;"> <img src='https://userpic.codeforces.org/1809311/avatar/8456dc0c30997ac5.jpg'/> </a> <div><a href="/profile/rag-hav" title="Expert rag-hav" class="rated-user user-blue">rag-hav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807186" href="?#comment-807186" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807183" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807186" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1809311" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807186"> <div class="moveup"> <div class="ttypography"><p>Isn't that exponential complexity? (two choices in every move)</p></div> </div> </div> <div class="reply info"> <a class="comment-807186 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807186 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807186"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807171" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/deletha" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/deletha" title="Pupil deletha" class="rated-user user-green">deletha</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807171" href="?#comment-807171" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807171" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1806788" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807171"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1539/submission/120173484" title="Посылка 120173484 от deletha">120173484</a> I am getting runtime error on test 23 in problem C. Unable to understand if it is due to seg fault or overflows. Can someone pls explain</p></div> </div> </div> <div class="reply info"> <a class="comment-807171 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807171 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807171"> <li> <div class="comment"> <table class="comment-table" commentId="807178" commentParentId="807171"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HowSoOrz" style="position: relative;"> <img src='https://userpic.codeforces.org/1519509/avatar/24d272c5a2a620a1.jpg'/> </a> <div><a href="/profile/HowSoOrz" title="Specialist HowSoOrz" class="rated-user user-cyan">HowSoOrz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 08:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807178" href="?#comment-807178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807171" style="font-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="807178" 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="807178" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1519509" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807178"> <div class="moveup"> <div class="ttypography"><p>Just return when the valid array size is 0. You cant use binary search when the size of the valid vector is 0. Reason: v.begin()=points to first element, v.end() points to next element of last ele.</p><p><a href="/contest/1539/submission/120176292" title="Посылка 120176292 от HowSoOrz">120176292</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807178"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807185" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noobKunal" style="position: relative;"> <img src='https://userpic.codeforces.org/1183443/avatar/73aa8f3ddfbcab8a.jpg'/> </a> <div><a href="/profile/noobKunal" title="Expert noobKunal" class="rated-user user-blue">noobKunal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807185" href="?#comment-807185" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807185" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1183443" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807185"> <div class="moveup"> <div class="ttypography"><p>Can anyone check <a href="https://codeforces.com/contest/1539/submission/120132934">my submission</a> for D. Its giving TLE at tc 11 and it seems that its because of initial sorting itself (and not even entering while loop).</p></div> </div> </div> <div class="reply info"> <a class="comment-807185 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807185 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807185"> <li> <div class="comment"> <table class="comment-table" commentId="807194" commentParentId="807185"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/i_aM_SnEhaal" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/i_aM_SnEhaal" title="Pupil i_aM_SnEhaal" class="rated-user user-green">i_aM_SnEhaal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807194" href="?#comment-807194" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807185" style="font-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="807194" 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="807194" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1279863" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807194"> <div class="moveup"> <div class="ttypography"><p>I tried to submit your solution with just by changing the compare function in sort and it worked. <a href="https://codeforces.com/contest/1539/submission/120179243">Here is the submission have a look</a> just compare it with your solution to see the changes I made.The problem was in how you are defining the compare function in sort. What I have understood is &lt;= or &gt;= is slower than &lt; or &gt; which is causing the problem. For more details please go through <a href="https://codeforces.com/blog/entry/70237">this blog</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-807194 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807194 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807194"> <li> <div class="comment"> <table class="comment-table" commentId="807201" commentParentId="807194"> <tr> <td class="left"> <div style="position: absolute; left: 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/noobKunal" style="position: relative;"> <img src='https://userpic.codeforces.org/1183443/avatar/73aa8f3ddfbcab8a.jpg'/> </a> <div><a href="/profile/noobKunal" title="Expert noobKunal" class="rated-user user-blue">noobKunal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807201" href="?#comment-807201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807194" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807201" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1183443" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807201"> <div class="moveup"> <div class="ttypography"><p>Thanks it passed. Wish i've known this before</p></div> </div> </div> <div class="reply info"> <a class="comment-807201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807201"> <li> <div class="comment"> <table class="comment-table" commentId="807205" commentParentId="807201"> <tr> <td class="left"> <div style="position: absolute; left: 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/i_aM_SnEhaal" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/i_aM_SnEhaal" title="Pupil i_aM_SnEhaal" class="rated-user user-green">i_aM_SnEhaal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807205" href="?#comment-807205" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807205" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1279863" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807205"> <div class="moveup"> <div class="ttypography"><p>I also learnt it the hard way. After getting TLE on TC 11 twice during the contest and then submitting the same code in 8 different ways after the contest was able to figure it out. </p></div> </div> </div> <div class="reply info"> <a class="comment-807205 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807205 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807205"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="1035068" commentParentId="807194"> <tr> <td class="left"> <div style="position: absolute; left: 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/BDboy" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BDboy" title="Expert BDboy" class="rated-user user-blue">BDboy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/05/2023 21:16">4 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1035068" href="?#comment-1035068" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807194" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1035068" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2468471" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1035068"> <div class="moveup"> <div class="ttypography"><p>Thanks, I wont be learning this the hard way. :)</p></div> </div> </div> <div class="reply info"> <a class="comment-1035068 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1035068 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1035068"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807188" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vkgainz" style="position: relative;"> <img src='https://userpic.codeforces.org/679880/avatar/f966b85a769e4f5.jpg'/> </a> <div><a href="/profile/vkgainz" title="Grandmaster vkgainz" class="rated-user user-red">vkgainz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:12">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807188" href="?#comment-807188" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807188" class="CommentVoteFrame" data-commentRating="51" data-commentUserId="679880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+51</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807188"> <div class="moveup"> <div class="ttypography"><p>I found D to be a lot easier to think about using binary search (which solves in $$$O(n\log(10^{14}))$$$. Similar to the editorial, sort with respect to $$$b_i$$$. Now, let $$$x$$$ be the number of items with price $$$1$$$ and $$$y$$$ be the number of items with price $$$2$$$. Then, our answer is equal to $$$x + 2 \cdot y = y + \sum_{i = 1} ^ {n} a_i$$$, so it suffices to minimize $$$y$$$.</p><p>Let's binary search on this. Suppose we set $$$y = k$$$. How do we know if this is enough? First we make two simple observations:</p> <ul> <li><p>We buy all $$$k$$$ items at the very beginning.</p></li> <li><p>We buy all $$$k$$$ items from a suffix of the sorted array.</p></li> </ul><p>Why does this work? Well, if you are going to buy $$$k$$$ items of price $$$2$$$, you should do it earlier than later, because then we might have more $$$b_i$$$ opened up that gives us items of price $$$1$$$. Similarly, we should be buying our items from a suffix because that way we can maximize the number of items of price $$$1$$$ we get (and, subsequently, minimize the number of items of price $$$2$$$). </p><p>From here it's simple to solve with binary search. To test $$$y = k$$$, start a counter for the number of items bought and an index at $$$0$$$. While the counter is greater than $$$b_{\text{index}}$$$, add $$$a_{\text{index}}$$$ to the counter (since we're getting all of those for price $$$1$$$) and increment the counter. If $$$k$$$ is enough, then the counter should be $$$\geq$$$ the number of items we have in total.</p><p>This explanation may seem a bit complicated, but the ideas involved are simple to arrive at and the implementation is very clean: <a href="https://codeforces.com/contest/1539/submission/120179122">my submission here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-807188 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807188 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807188"> <li> <div class="comment"> <table class="comment-table" commentId="807238" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ace-in-the-hole" style="position: relative;"> <img src='https://userpic.codeforces.org/725810/avatar/31d6d37857b526e4.jpg'/> </a> <div><a href="/profile/ace-in-the-hole" title="Candidate Master ace-in-the-hole" class="rated-user user-violet">ace-in-the-hole</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 12:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807238" href="?#comment-807238" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807238" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="725810" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807238"> <div class="moveup"> <div class="ttypography"><p>This idea is nice, but it's still not too different from the solution, because we still have to make the observation: buying items with higher b_i is better. I can say, your idea is <strong>not fundamentally different</strong> from the solution's idea. Maybe because this is not a hard problem so we can't see the diversity of the solutions like some others.</p><p>But it sure is a great idea, the thoughts &quot;I should minimize the number of bought items with price 2&quot;, &quot;I can binary search the answer on this&quot;, ... and more, as you explained, are completely natural and can be thought of. Thank you for your contribution!</p></div> </div> </div> <div class="reply info"> <a class="comment-807238 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807238 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807238"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807334" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/faraz16iqbal" style="position: relative;"> <img src='https://userpic.codeforces.org/1534426/avatar/6269999f6a6fd0c7.jpg'/> </a> <div><a href="/profile/faraz16iqbal" title="Expert faraz16iqbal" class="rated-user user-blue">faraz16iqbal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 17:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807334" href="?#comment-807334" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807334" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1534426" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807334"> <div class="moveup"> <div class="ttypography"><p>Thank you, brilliant explanation</p></div> </div> </div> <div class="reply info"> <a class="comment-807334 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807334 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807334"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807893" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeerInForestovo" style="position: relative;"> <img src='https://userpic.codeforces.org/805889/avatar/8210f0230414d9cc.jpg'/> </a> <div><a href="/profile/DeerInForestovo" title="Master DeerInForestovo" class="rated-user user-orange">DeerInForestovo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 12:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807893" href="?#comment-807893" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807893" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="805889" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807893"> <div class="moveup"> <div class="ttypography"><p>Thanks. In your solution, we finally found a proper position where the things before it were 1 and later than it were 2. So, why not check every possible position and keep some useful information? See <a href="https://codeforces.com/contest/1539/submission/120329507">my submission</a>, which is theoretically O(N) if we use radix sort instead of qsort.</p><p>Sorry for my bad English : )</p></div> </div> </div> <div class="reply info"> <a class="comment-807893 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807893 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807893"> <li> <div class="comment"> <table class="comment-table" commentId="807895" commentParentId="807893"> <tr> <td class="left"> <div style="position: absolute; left: 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/DeerInForestovo" style="position: relative;"> <img src='https://userpic.codeforces.org/805889/avatar/8210f0230414d9cc.jpg'/> </a> <div><a href="/profile/DeerInForestovo" title="Master DeerInForestovo" class="rated-user user-orange">DeerInForestovo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 12:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807895" href="?#comment-807895" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807893" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807895" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="805889" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807895"> <div class="moveup"> <div class="ttypography"><p>In my submission, 'Hab' meant 'Had bought'</p></div> </div> </div> <div class="reply info"> <a class="comment-807895 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807895 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807895"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="868233" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yeetholmes619" style="position: relative;"> <img src='https://userpic.codeforces.org/1957631/avatar/1ad3067143e8096e.jpg'/> </a> <div><a href="/profile/yeetholmes619" title="Expert yeetholmes619" class="rated-user user-blue">yeetholmes619</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/17/2021 01:45">22 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-868233" href="?#comment-868233" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="868233" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1957631" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-868233"> <div class="moveup"> <div class="ttypography"><p>I'm sorry for replying to your comment that is 6 months old, but reading this cleared all my doubts and troubles with this problem, I struggled with finding the right train of thought to solve this problem and the way you explained it removed all of my confusion regarding this.</p><p>The two pointer technique althought gives AC, didn't make the underlying idea behind the solution, i.e x+2y will be our minimum cost which can be re-written as ∑ai + y obvious to me, which your approach clearly does. Thanks a lot! your comment not only helped me in this problem but will help me in future problems as well as it gave light to the right mindset while solving the problem :)</p></div> </div> </div> <div class="reply info"> <a class="comment-868233 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-868233 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-868233"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807217" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Delver0227" style="position: relative;"> <img src='https://userpic.codeforces.org/1594171/avatar/5f6e96d412ba3fde.jpg'/> </a> <div><a href="/profile/Delver0227" title="Specialist Delver0227" class="rated-user user-cyan">Delver0227</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 10:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807217" href="?#comment-807217" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807217" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1594171" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807217"> <div class="moveup"> <div class="ttypography"><p>I have a different way of implementing problem D that is more concise. Considering buying items backwards, we want to the last item we buy is the item with the highest discount requirement(which can be achieved). Which means all we need to do is suppose we have already bought all the items and the number of items is $$$num$$$. Sorting $$$b_i$$$ in non-decreasing order, skip the items that are impossible to get a discount on and take $$$num_i = \min(num-b_i,a_i)$$$ as the number of $$$item_i$$$ which we can buy with a discount. Remember to substract $$$num_i$$$ from $$$num$$$. After iterating $$$i$$$ through all the items, the sum of $$$num_i$$$ is the total number of item that we can get a discount on.</p><p>The code goes like this:<a href="https://paste.ubuntu.com/p/8mwW8n2yfQ/">https://paste.ubuntu.com/p/8mwW8n2yfQ/</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807217 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807217 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807217"> <li> <div class="comment"> <table class="comment-table" commentId="809490" commentParentId="807217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Whimpers" style="position: relative;"> <img src='https://userpic.codeforces.org/1507315/avatar/b11dc9bbdf35d8d9.jpg'/> </a> <div><a href="/profile/Whimpers" title="Expert Whimpers" class="rated-user user-blue">Whimpers</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 03:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809490" href="?#comment-809490" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809490" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1507315" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809490"> <div class="moveup"> <div class="ttypography"><p>why does this work? dont 1's also count towards the total items bought. from what i can see from your solution it is just comparing if the number of items left is greater than the b of the current last item, but if there is an item that has a lot more a than it has b, wouldnt it also be useful in increasing the total number bought and thus would have to be used in the total number of items bought?</p></div> </div> </div> <div class="reply info"> <a class="comment-809490 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809490 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809490"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807229" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Samrev" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Samrev" title="Expert Samrev" class="rated-user user-blue">Samrev</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 11:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807229" href="?#comment-807229" style="font-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="807229" 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="807229" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="1932888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807229"> <div class="moveup"> <div class="ttypography"><p>Test:</p> <pre><code>5 3 10 2 12 1 11 3 10 1 8 </code></pre><p>Submission: <a href="/contest/1539/submission/120129309" title="Посылка 120129309 от Kakashi_099">120129309</a></p><p>Output : 20 Correct Output: 19</p><p>This submission is getting accepted but however the above test case shows wrong output. Correct Output should be 19, instead of 20.</p><p><a class="rated-user user-red" href="/profile/talant" title="Гроссмейстер talant">talant</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807229 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807229 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807229"> <li> <div class="comment"> <table class="comment-table" commentId="807256" commentParentId="807229"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/talant" style="position: relative;"> <img src='https://userpic.codeforces.org/1215930/avatar/cc80e217f41ccfb0.jpg'/> </a> <div><a href="/profile/talant" title="Grandmaster talant" class="rated-user user-red">talant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807256" href="?#comment-807256" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807229" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807256" class="CommentVoteFrame" data-commentRating="58" data-commentUserId="1215930" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+58</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807256"> <div class="moveup"> <div class="ttypography"><p>Stop tagging me, this task isn't even mine</p></div> </div> </div> <div class="reply info"> <a class="comment-807256 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807256 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807256"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807232" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Anish_Bashyal" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Anish_Bashyal" title="Pupil Anish_Bashyal" class="rated-user user-green">Anish_Bashyal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 12:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807232" href="?#comment-807232" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807232" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1411502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807232"> <div class="moveup"> <div class="ttypography"><p><strong>Problem D</strong></p><p>Proof that buying more items of some product than needed doesn't make the answer better. Let's suppose we have already achieved an product (say product A) which we can buy at discount. Now consider we have to buy next product (say product B). </p><p><strong>N</strong> be the number of product B we have to buy, and <strong>d</strong> be the total purchases required before discount and <strong>c</strong> be the amount of items we have already purchased. Then, </p><p><strong>Case I (buy more of product A and then B)</strong></p><p>Total cost for buying product B = <strong>(d-c)*1 + (N*1)</strong> = <strong>d-c+N</strong></p><p><strong>Case II (only buying product B)</strong></p><p>Total cost for buying product B = <strong>2 * (d-c) + ( N-( d-c ) )</strong> = <strong>d-c+N</strong> </p><p>So both the cases cost the same. But this is a special scenario. If we had different percentage of discount, then the above cases wouldn't be equal. </p><p>If we say <strong>m</strong> as discount percentage and <strong>x</strong> as normal price then, </p><p><strong>Case I</strong></p><p><em>mx(d-c) + Nmx</em></p><p><strong>Case II</strong></p><p><em>x(d-c) + (N-d+c)mx</em></p><p>Equating both cases, we get <strong>m = 0.5 or 50%</strong>..</p><p>So only when the discount percentage is 50%, buying more of a discounted product or buying only the required quantity of each products doesn't matter. Hence also in this case, doesn't matter.</p><p>Sorry for writing just the obvious algebra but wanted to share anyway :)</p></div> </div> </div> <div class="reply info"> <a class="comment-807232 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807232 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807232"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807240" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hurt_FOR_heart" style="position: relative;"> <img src='https://userpic.codeforces.org/1445761/avatar/4bd86d3c8cfb747a.jpg'/> </a> <div><a href="/profile/hurt_FOR_heart" title="Candidate Master hurt_FOR_heart" class="rated-user user-violet">hurt_FOR_heart</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807240" href="?#comment-807240" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807240" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="1445761" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807240"> <div class="moveup"> <div class="ttypography"><p>in E</p> <ul> <li>Card in query i fits constraints on value written on card in left hand in queries with indexes [i,j).</li> </ul><p>i think it's [i,j] isn't it ? Because we have card in i for query j too </p></div> </div> </div> <div class="reply info"> <a class="comment-807240 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807240 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807240"> <li> <div class="comment"> <table class="comment-table" commentId="807271" commentParentId="807240"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TeaTime" style="position: relative;"> <img src='https://userpic.codeforces.org/1199093/avatar/f1cbbd424f7d3cf7.jpg'/> </a> <div><a href="/profile/TeaTime" title="Master TeaTime" class="rated-user user-orange">TeaTime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:25">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807271" href="?#comment-807271" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807240" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807271" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="1199093" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807271"> <div class="moveup"> <div class="ttypography"><p>It's [i, j) because card j was already taken in right hand.</p></div> </div> </div> <div class="reply info"> <a class="comment-807271 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807271 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807271"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807273" commentParentId="807240"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TeaTime" style="position: relative;"> <img src='https://userpic.codeforces.org/1199093/avatar/f1cbbd424f7d3cf7.jpg'/> </a> <div><a href="/profile/TeaTime" title="Master TeaTime" class="rated-user user-orange">TeaTime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807273" href="?#comment-807273" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807240" style="font-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="807273" 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="807273" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="1199093" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807273"> <div class="moveup"> <div class="ttypography"><p>Oh, you are correct, I mistook it with something else. Thanks for noticing!</p><p>Edit: editorial was fixed.</p></div> </div> </div> <div class="reply info"> <a class="comment-807273 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807273 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807273"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807241" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pucuk16" style="position: relative;"> <img src='https://userpic.codeforces.org/1458650/avatar/a688a695b97d78cb.jpg'/> </a> <div><a href="/profile/pucuk16" title="Newbie pucuk16" class="rated-user user-gray">pucuk16</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807241" href="?#comment-807241" style="font-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="807241" 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="807241" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1458650" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807241"> <div class="moveup"> <div class="ttypography"><p>hai.. where my code gone wrong..? please help me..<br /> for problem C <br /> thx <a href="https://codeforces.com/contest/1539/submission/120116110">code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807241"> <li> <div class="comment"> <table class="comment-table" commentId="807335" commentParentId="807241"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bwxnQAQ" style="position: relative;"> <img src='https://userpic.codeforces.org/1816180/avatar/1179db2c2821d194.jpg'/> </a> <div><a href="/profile/bwxnQAQ" title="Expert bwxnQAQ" class="rated-user user-blue">bwxnQAQ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 17:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807335" href="?#comment-807335" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807241" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807335" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="1816180" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807335"> <div class="moveup"> <div class="ttypography"><p>You should check line 37.You change d continuously without initializing.The d on the right side of each formula in line 37 should be the d in line 32 instead of the last calculated d.</p></div> </div> </div> <div class="reply info"> <a class="comment-807335 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807335 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807335"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807251" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spookywooky" style="position: relative;"> <img src='https://userpic.codeforces.org/872585/avatar/a8efaf71cbe05928.jpg'/><img title='Почетный бейдж за поддержку Codeforces на его 10-летие' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/spookywooky" title="Specialist spookywooky" class="rated-user user-cyan">spookywooky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807251" href="?#comment-807251" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807251" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="872585" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807251"> <div class="moveup"> <div class="ttypography"><p>Explanation to E sounds like it would be possible to explain it in an understandable way.</p></div> </div> </div> <div class="reply info"> <a class="comment-807251 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807251 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807251"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807258" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807258" href="?#comment-807258" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807258" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807258"> <div class="moveup"> <div class="ttypography"><p><strong>If there is an item which costs 1, then we will not make the answer worse by buying this item.</strong></p><p>Why is that? For example, consider a situation where we've already bought all items, except for one, and it costs 2, and to make it cost 1 we need to buy 2 more items. In that case it would be cheaper to buy one left item and spend 2 instead of buing two more random items at cost 1 and finally buing one last item, spending 3 in total.</p></div> </div> </div> <div class="reply info"> <a class="comment-807258 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807258 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807258"> <li> <div class="comment"> <table class="comment-table" commentId="807275" commentParentId="807258"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807275" href="?#comment-807275" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807258" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807275" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807275"> <div class="moveup"> <div class="ttypography"><p>In your example you are explicitly making the cost of that item by buying more products of other items. But the statement means that if by buying other items and within limits i.e. less that $$$a_i$$$, then you should buy the items of cost 1.</p></div> </div> </div> <div class="reply info"> <a class="comment-807275 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807275 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807275"> <li> <div class="comment"> <table class="comment-table" commentId="807277" commentParentId="807275"> <tr> <td class="left"> <div style="position: absolute; left: 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/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:54">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807277" href="?#comment-807277" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807277" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807277"> <div class="moveup"> <div class="ttypography"><p>Thanks, that explains it:)</p></div> </div> </div> <div class="reply info"> <a class="comment-807277 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807277 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807277"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807331" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/NoobCpp" style="position: relative;"> <img src='https://userpic.codeforces.org/1716219/avatar/14a123abec8289d0.jpg'/> </a> <div><a href="/profile/NoobCpp" title="Specialist NoobCpp" class="rated-user user-cyan">NoobCpp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 17:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807331" href="?#comment-807331" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807331" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1716219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807331"> <div class="moveup"> <div class="ttypography"><p>Although E and F was more difficult than the rest, the contest was great. First time reach to Expert!!</p><p>Sr about my bad Eng :p</p></div> </div> </div> <div class="reply info"> <a class="comment-807331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807331"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807364" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/livlyf_168" style="position: relative;"> <img src='https://userpic.codeforces.org/1919608/avatar/cf064edf00e3eea6.jpg'/> </a> <div><a href="/profile/livlyf_168" title="Pupil livlyf_168" class="rated-user user-green">livlyf_168</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807364" href="?#comment-807364" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807364" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1919608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807364"> <div class="moveup"> <div class="ttypography"><p>Hey, can anyone help me with problem C. Don't know why is it giving WA on test 10. Below is my submission — <a href="/contest/1539/submission/120223010" title="Посылка 120223010 от livlyf_168">120223010</a>. I have used the same approach, except that I have taken The number of elements required to fill the gap as floor((d-1)/x). </p></div> </div> </div> <div class="reply info"> <a class="comment-807364 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807364 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807364"> <li> <div class="comment"> <table class="comment-table" commentId="807370" commentParentId="807364"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/itish" style="position: relative;"> <img src='https://userpic.codeforces.org/1589684/avatar/d4fea913edfbab4b.jpg'/> </a> <div><a href="/profile/itish" title="Candidate Master itish" class="rated-user user-violet">itish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807370" href="?#comment-807370" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807364" style="font-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="807370" 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="807370" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1589684" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807370"> <div class="moveup"> <div class="ttypography"><p>Change vector(int)split to vector(llint) split and it gets accepted</p></div> </div> </div> <div class="reply info"> <a class="comment-807370 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807370 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807370"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807374" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hotas" style="position: relative;"> <img src='https://userpic.codeforces.org/1150129/avatar/590cdb757ae4763a.jpg'/> </a> <div><a href="/profile/Hotas" title="Newbie Hotas" class="rated-user user-gray">Hotas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807374" href="?#comment-807374" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807374" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1150129" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807374"> <div class="moveup"> <div class="ttypography"><p>Can anyone tell me where am I doing wrong? I am getting wrong answer on test case 10. Problem C. Submission : <a href="/contest/1539/submission/120227942" title="Посылка 120227942 от Hotas">120227942</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807374 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807374 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807374"> <li> <div class="comment"> <table class="comment-table" commentId="807397" commentParentId="807374"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 20:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807397" href="?#comment-807397" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807374" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807397" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807397"> <div class="moveup"> <div class="ttypography"><p>I think the problem is that you have int[] a instead of ll[] a. Each element can be up to 1e18.</p></div> </div> </div> <div class="reply info"> <a class="comment-807397 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807397 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807397"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807378" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/coderaman327" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/coderaman327" title="Expert coderaman327" class="rated-user user-blue">coderaman327</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807378" href="?#comment-807378" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807378" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="886853" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807378"> <div class="moveup"> <div class="ttypography"><p>Can someone please tell me what my mistake is in problem D? <a href="https://codeforces.com/contest/1539/submission/120100696">My submission</a> Thanks in advance!!</p></div> </div> </div> <div class="reply info"> <a class="comment-807378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807378"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807400" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abyboi" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/abyboi" title="Pupil abyboi" class="rated-user user-green">abyboi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 21:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807400" href="?#comment-807400" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807400" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1833158" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807400"> <div class="moveup"> <div class="ttypography"><p>Can someone help me with Problem D? My submission is</p><p><a href="https://codeforces.com/contest/1539/submission/120232784">https://codeforces.com/contest/1539/submission/120232784</a></p><p>Thanks in advance!</p></div> </div> </div> <div class="reply info"> <a class="comment-807400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807400"> <li> <div class="comment"> <table class="comment-table" commentId="807478" commentParentId="807400"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/andr14142" style="position: relative;"> <img src='https://userpic.codeforces.org/620444/avatar/368d81a28bf4f89b.jpg'/> </a> <div><a href="/profile/andr14142" title="Pupil andr14142" class="rated-user user-green">andr14142</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 09:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807478" href="?#comment-807478" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807400" style="font-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="807478" 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="807478" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="620444" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807478"> <div class="moveup"> <div class="ttypography"><p>Your solution has not correct comparison in the case of whole buying goods without discount:<br /> else if (total_bought + products[j].F &lt; products[i].S)<br /> Correct comparison is:<br /> else if (total_bought + products[j].F &lt;= products[i].S)</p></div> </div> </div> <div class="reply info"> <a class="comment-807478 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807478 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807478"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807520" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Madara_Uzumaki" style="position: relative;"> <img src='https://userpic.codeforces.org/1621901/avatar/28eb09a48344e5fb.jpg'/> </a> <div><a href="/profile/Madara_Uzumaki" title="Newbie Madara_Uzumaki" class="rated-user user-gray">Madara_Uzumaki</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 11:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807520" href="?#comment-807520" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807520" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1621901" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807520"> <div class="moveup"> <div class="ttypography"><p>In <strong>problem</strong> C i ran the code in <strong>PyPy3</strong> the code got <strong>TLE in test case 18</strong> but when I ran the same code in <strong>Python3</strong> the code got <strong>accepted</strong> Can anyone clarify why did that happen?</p></div> </div> </div> <div class="reply info"> <a class="comment-807520 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807520 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807520"> <li> <div class="comment"> <table class="comment-table" commentId="807527" commentParentId="807520"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/casul" style="position: relative;"> <img src='https://userpic.codeforces.org/1690955/avatar/21ae0e21fe431dd7.jpg'/> </a> <div><a href="/profile/casul" title="Specialist casul" class="rated-user user-cyan">casul</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 12:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807527" href="?#comment-807527" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807520" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807527" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1690955" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807527"> <div class="moveup"> <div class="ttypography"><p>You may wanna check out this blog:</p><p><a href="https://codeforces.com/blog/entry/82989">https://codeforces.com/blog/entry/82989</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807527 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807527 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807527"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807629" commentParentId="807520"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aberent" 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/aberent" title="Specialist aberent" class="rated-user user-cyan">aberent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 18:13">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807629" href="?#comment-807629" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807520" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807629" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1157884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807629"> <div class="moveup"> <div class="ttypography"><p>I too got some strange behaviour with PyPy3 with test 18. Every version I tried printed a result and then (after it should have finished), got TLE. I wonder whether there is a bug somewhere here. See <a href="https://codeforces.com/blog/entry/92011">my blog entry</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-807629 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807629 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807629"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807566" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zvsevolod" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/zvsevolod" title="Newbie zvsevolod" class="rated-user user-gray">zvsevolod</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 14:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807566" href="?#comment-807566" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807566" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1271216" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807566"> <div class="moveup"> <div class="ttypography"><p>In problem C Java solution with Long[] array gets accepted, but long[] array solution gets TLE. (16th line in both solutions) </p><p>ACC: <a href="https://codeforces.com/contest/1539/submission/120284760">https://codeforces.com/contest/1539/submission/120284760</a> <br /> TLE: <a href="https://codeforces.com/contest/1539/submission/120284797">https://codeforces.com/contest/1539/submission/120284797</a></p><p>Could someone explain me why reference type works faster than primitive in this example?</p></div> </div> </div> <div class="reply info"> <a class="comment-807566 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807566 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807566"> <li> <div class="comment"> <table class="comment-table" commentId="807620" commentParentId="807566"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aberent" 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/aberent" title="Specialist aberent" class="rated-user user-cyan">aberent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 18:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807620" href="?#comment-807620" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807566" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807620" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1157884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807620"> <div class="moveup"> <div class="ttypography"><p>Apparently Java uses different sorting algorithms for integers (including longs) and objects. The algorithm for integers is generally faster, but its worst case is worse. You might have simply been unlucky. See the implementation notes for the two versions of sort: <a href="https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(long%5B%5D">https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(long%5B%5D</a>) <a href="https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(java.lang.Object%5B%5D">https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(java.lang.Object%5B%5D</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-807620 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807620 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807620"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807726" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/quinoa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/quinoa" title="Expert quinoa" class="rated-user user-blue">quinoa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 23:40">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807726" href="?#comment-807726" style="font-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="807726" 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="807726" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="592293" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807726"> <div class="moveup"> <div class="ttypography"><p>I had a hard time understanding the tutorial for problem E. This is my attempt at making it easier to understand.</p><p><strong>Easier problem: jump game</strong></p><p>Consider <a href="https://leetcode.com/problems/jump-game/">this</a> easier problem: you have an array $$$x$$$ where $$$x[i]$$$ means what the farthest is that you can jump from position $$$i$$$. Is it possible to reach the last element in the array if you start from position 0?</p><p>We can solve it with a DP where $$$dp[i]$$$ = can we reach the end if we start from position i? The solution to the problem is then equal to $$$dp[0]$$$. The transitions are like this: $$$dp[i]$$$ = $$$dp[i + 1]$$$ $$$||$$$ $$$dp[i + 2]$$$ $$$||$$$ ... $$$||$$$ $$$dp[i + x[i]]$$$. There are $$$N$$$ states and the transitions are $$$O(N)$$$ so this runs in $$$O(N^2)$$$.</p><p>We can make every transition $$$O(1)$$$ with a greedy insight. Instead of checking $$$dp[i + 1]$$$, ..., $$$dp[i + x[i]]$$$ we only need to check $$$dp[j]$$$ where $$$j$$$ is the leftmost position from which we can reach the end. The reason this works is that the leftmost position from which we can reach the end has the best probability of being within our jumping range. We can keep track of this leftmost position as we compute each state in a bottom up fashion.</p> <pre><code>int leftmost_possible = N - 1; for (int i = N - 2; i &gt;= 0; --i) { if (leftmost_possible &lt;= i + x[i]) { dp[i] = true; leftmost_possible = i; } } </code></pre><p><strong>Back to problem E</strong></p><p>We can again solve this with an $$$O(N^2)$$$ DP where $$$dp(x, y)$$$ = can we finish if card with index $$$x$$$ is in the left hand, and card with index $$$y$$$ is in the right hand (and we have just answered query $$$max(x, y)$$$). </p><p>We can notice that we can reduce the number of states to $$$N$$$. Because if we are at $$$dp(x, y)$$$ (WLOG $$$x &gt; y$$$) then</p> <ul> <li>either we will keep replacing the card in the left hand until we reach the end</li> <li>or at some point we have to take something in the right hand and we transition to state $$$dp(k, k + 1)$$$</li> </ul><p>So if we are at state (x, y) then in the next step either we are done, or we will transition to $$$dp(k, k + 1)$$$. Therefore (since we start at state $$$dp(0, 1)$$$) we will only visit states of the type $$$dp(k, k + 1)$$$ (and $$$dp(k - 1, k)$$$), and there are only $$$O(N)$$$ of those.</p><p>The transition is now $$$O(N)$$$ because we have to consider every $$$k$$$ such that $$$dp(k, k + 1)$$$ works. But with the same greedy insight as in the jump game problem we can reduce that to $$$O(1)$$$. Again we can store &quot;the leftmost k that works&quot; as we compute the states and therefore we can find the transition in $$$O(1)$$$.</p><p>Now of course in this problem another hard part is to compute the &quot;maximum jump length&quot; at every position. In the jump game problem this was given in the input, whereas here we have to compute it. For sure you can do it in logarithmic time with a segment tree (I saw it in <a href="https://www.youtube.com/watch?v=seaskdKf2sI">Colin Galen's video</a>). But apparently you can also do it in $$$O(1)$$$ since the solution runs in O(N) according to the tutorial. I didn't think about optimizing that part yet.</p></div> </div> </div> <div class="reply info"> <a class="comment-807726 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807726 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807726"> <li> <div class="comment"> <table class="comment-table" commentId="852194" commentParentId="807726"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ahshafi" style="position: relative;"> <img src='https://userpic.codeforces.org/818506/avatar/d65d006cfdce087a.jpg'/> </a> <div><a href="/profile/ahshafi" title="Candidate Master ahshafi" class="rated-user user-violet">ahshafi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/19/2021 17:24">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-852194" href="?#comment-852194" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807726" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="852194" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="818506" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-852194"> <div class="moveup"> <div class="ttypography"><p>me too confused about how to compute maximum jump length in O(1) </p></div> </div> </div> <div class="reply info"> <a class="comment-852194 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-852194 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-852194"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808157" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sg55" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sg55" title="Newbie sg55" class="rated-user user-gray">sg55</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/24/2021 05:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808157" href="?#comment-808157" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808157" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1445980" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808157"> <div class="moveup"> <div class="ttypography"><p>I have used 2 the same method as used by most of the other coders but my code is giving tle. Can please someone look and tell me why it is? <a href="/contest/1539/submission/120407076" title="Посылка 120407076 от sg55">120407076</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808157 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808157 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808157"> <li> <div class="comment"> <table class="comment-table" commentId="808253" commentParentId="808157"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zvsevolod" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/zvsevolod" title="Newbie zvsevolod" class="rated-user user-gray">zvsevolod</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/24/2021 13:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808253" href="?#comment-808253" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808157" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808253" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1271216" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808253"> <div class="moveup"> <div class="ttypography"><p>Try to use Long[] array instead of long[]. Also you may read my comment above.</p></div> </div> </div> <div class="reply info"> <a class="comment-808253 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808253 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808253"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hritik27" style="position: relative;"> <img src='https://userpic.codeforces.org/1232410/avatar/af014e1c10ef2a19.jpg'/> </a> <div><a href="/profile/hritik27" title="Newbie hritik27" class="rated-user user-gray">hritik27</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/24/2021 19:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808320" href="?#comment-808320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808320" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1232410" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808320"> <div class="moveup"> <div class="ttypography"><p>Can someone please help me with problem A?? Can't understand the solution give.</p></div> </div> </div> <div class="reply info"> <a class="comment-808320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808320"> <li> <div class="comment"> <table class="comment-table" commentId="810306" commentParentId="808320"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/songzy12" style="position: relative;"> <img src='https://userpic.codeforces.org/249570/avatar/3c83a5ef255ff4d6.jpg'/> </a> <div><a href="/profile/songzy12" title="Pupil songzy12" class="rated-user user-green">songzy12</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/30/2021 17:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810306" href="?#comment-810306" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808320" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810306" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="249570" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810306"> <div class="moveup"> <div class="ttypography"><p>1. First consider the case where there are infinite participants. Then each participant would be disturbed by $$$t/x$$$ participants following him. </p><p>2. Then consider the case that $$$n$$$ is finite but large enough, then the first participant would be disturbed by $$$t/x$$$, the same for participant 2, ..., until $$$k$$$. </p><p>For the participants beyond k, the number of participants that would disturb them are decreased by 1 each time, i.e., $$$t/x - 1$$$, $$$t/x - 2$$$, until 0 for the last participant.</p><p>There are $$$t/x$$$ numbers from $$$t/x - 1$$$ until 0, thus we know $$$k = n - t/x$$$.</p><p>So the answer would be $$$(n-t/x) * (t/x) + (t/x-1)*(t/x)/2$$$.</p><p>3. The $$$min$$$ and $$$max$$$ in the answer is to solve the case where n is not large enough, i.e., when $$$n &lt; t/x$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-810306 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810306 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810306"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808360" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/augurar" style="position: relative;"> <img src='https://userpic.codeforces.org/391071/avatar/8a814e47f9aacb44.jpg'/> </a> <div><a href="/profile/augurar" title="Expert augurar" class="rated-user user-blue">augurar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 02:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808360" href="?#comment-808360" style="font-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="808360" 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="808360" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="391071" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808360"> <div class="moveup"> <div class="ttypography"><p>I'm glad I didn't participate in this one officially. Problem C was easy but I kept getting a TLE for stupid language-specific reasons:</p> <ul> <li><p>My <a href="https://codeforces.com/contest/1539/submission/120478273">Python solution</a> got TLE on test 18 with PyPy3, but the same code passed with Python 3.</p></li> <li><p>My <a href="https://codeforces.com/contest/1539/submission/120478521">Java solution</a> got TLE on test 61, but passed if I changed <code>long[]</code> to <code>Long[]</code>. (This is kind of my fault for not knowing Java uses a worst-case O(n^2) sort for primitive arrays.)</p></li> <li><p>My <a href="https://codeforces.com/contest/1539/submission/120480356">C++ solution</a> passed with no special optimization.</p></li> </ul><p>In my opinion that's an indication that the time limit is overly strict, especially for an ABC problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-808360 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808360 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808360"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="816645" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/comseung18_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/comseung18_" title="Expert comseung18_" class="rated-user user-blue">comseung18_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/15/2021 09:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-816645" href="?#comment-816645" style="font-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="816645" 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="816645" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275870" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-816645"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1539/submission/122552751" title="Посылка 122552751 от comseung18_">122552751</a> why my solution A is not correct ? ans1 is Editorial solution ans2 is my solution</p><p>I checked my ans2 in many times. but ans1 equals ans2..<br />~~~~~ import random k = int(input()) for _ in range(k): n = random.randint(1,2*1000000000) x = random.randint(1,2*1000000000) t = random.randint(1,2*1000000000) tmp = t//x ans1 = max(0,n-tmp)*tmp + min(n-1,tmp-1)*min(n,tmp)//2 ans2 = tmp*n — tmp*tmp + tmp*n — ((2*n-tmp+1)*tmp)//2 if ans1 != ans2: print(ans1,ans2) ~~~~~</p></div> </div> </div> <div class="reply info"> <a class="comment-816645 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-816645 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-816645"> <li> <div class="comment"> <table class="comment-table" commentId="816647" commentParentId="816645"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/comseung18_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/comseung18_" title="Expert comseung18_" class="rated-user user-blue">comseung18_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/15/2021 09:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-816647" href="?#comment-816647" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-816645" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="816647" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275870" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-816647"> <div class="moveup"> <div class="ttypography"><p>when , t/x &gt; n , ans2 is wrong sorry</p></div> </div> </div> <div class="reply info"> <a class="comment-816647 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-816647 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-816647"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="984743" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PrickyToTheMoon" style="position: relative;"> <img src='https://userpic.codeforces.org/1432360/avatar/422cb9d88c769b8d.jpg'/> </a> <div><a href="/profile/PrickyToTheMoon" title="Pupil PrickyToTheMoon" class="rated-user user-green">PrickyToTheMoon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/24/2022 21:10">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-984743" href="?#comment-984743" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="984743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1432360" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-984743"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1539/submission/186604051" title="Submission 186604051 by PrickyToTheMoon">186604051</a></p><p>Please help. Cannot understand why getting WA on test case 18. My approach matches perfectly with editorial.</p><p>Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-984743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-984743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-984743"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="995447" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mohsina_Shaikh" style="position: relative;"> <img src='https://userpic.codeforces.org/1396580/avatar/6f21616a2d8d578.jpg'/> </a> <div><a href="/profile/Mohsina_Shaikh" title="Newbie Mohsina_Shaikh" class="rated-user user-gray">Mohsina_Shaikh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/25/2023 07:37">8 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-995447" href="?#comment-995447" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="995447" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1396580" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-995447"> <div class="moveup"> <div class="ttypography"><p>can anyone please explain how problem B can be solved using DP.</p></div> </div> </div> <div class="reply info"> <a class="comment-995447 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-995447 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-995447"> </ul> </div> <br/> <div id="editBox-100475" 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 firstPreview100475 = true; var lastPreviewContent100475 = ''; 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=100475] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=100475] 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-92516").click(function () { $.post("/data/topic/vote", {topicId: 92516, _tta: Codeforces.tta(), topicRevisionId: 229854, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-92516").click(function () { $.post("/data/topic/vote", {topicId: 92516, _tta: Codeforces.tta(), topicRevisionId: 229854, 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:33:26</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:'81289365b9230c42',t:'MTY5NjcwNzIwNi44NDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1539C
1539
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$$$. Уровень знаний $$$i$$$-го ученика равен $$$a_i$$$. Всех учеников нужно распределить на <span class="tex-font-style-it">стабильные группы</span>. Группа называется <span class="tex-font-style-it">стабильной</span>, если после сортировки всех учеников группы в порядке возрастания их уровня знаний у любых двух подряд идущих учеников разница уровня знаний не превосходит $$$x$$$.</p><p>Например, при $$$x = 4$$$ группа с уровнями знаний $$$[1, 10, 8, 4, 4]$$$ является стабильной (потому что $$$4 - 1 \le x$$$, $$$4 - 4 \le x$$$, $$$8 - 4 \le x$$$, $$$10 - 8 \le x$$$), а группа с уровнями $$$[2, 10, 10, 7]$$$ не является стабильной ($$$7 - 2 = 5 &gt; x$$$).</p><p>Преподаватели — достаточно находчивые люди, поэтому в дополнение к $$$n$$$ имеющимся ученикам они могут пригласить не более $$$k$$$ дополнительных учеников с <span class="tex-font-style-bf">любым</span> уровнем знаний на выбор преподавателей. Определите минимальное число стабильных групп, на которые можно распределить всех учеников (возможно, пригласив новых учеников).</p><p>Например, если есть два ученика с уровнями знаний $$$1$$$ и $$$5$$$, $$$x = 2$$$, и $$$k \ge 1$$$, то можно пригласить ученика с уровнем знаний $$$3$$$ и определить всех учеников в одну стабильную группу.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся три целых числа $$$n$$$, $$$k$$$, $$$x$$$ ($$$1 \le n \le 200\,000$$$, $$$0 \le k \le 10^{18}$$$, $$$1 \le x \le 10^{18}$$$) — количество учеников, сколько учеников можно пригласить дополнительно и максимальная допустимая разница уровня знаний.</p><p>Во второй строке вводится $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^{18}$$$) — уровни знаний учеников.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В единственной строке выведите одно число — искомое минимальное число стабильных групп, на которое можно разбить учеников.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 8 2 3 1 1 5 8 12 13 20 22 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 13 0 37 20 20 80 70 70 70 420 5 1 5 1 60 90 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере из условия можно пригласить учеников с уровнями знаний, равными $$$2$$$ и $$$11$$$. Тогда учеников можно разделить на следующие стабильные группы: </p><ol> <li> $$$[1, 1, 2, 5, 8, 11, 12, 13]$$$, </li><li> $$$[20, 22]$$$. </li></ol><p>Во втором примере из условия новых учеников приглашать нельзя, поэтому потребуется $$$3$$$ группы: </p><ol> <li> $$$[1, 1, 5, 5, 20, 20]$$$ </li><li> $$$[60, 70, 70, 70, 80, 90]$$$ </li><li> $$$[420]$$$ </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="fec63598679f3f0fe689e462d0b3c45b"/> <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="3b3d6aa18ec7f2c8636f747ba32c1b3c7997564d"/> <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='fec63598679f3f0fe689e462d0b3c45b'>&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%2F1539%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='fec63598679f3f0fe689e462d0b3c45b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1539">Codeforces Round 727 (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='fec63598679f3f0fe689e462d0b3c45b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1539/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='fec63598679f3f0fe689e462d0b3c45b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1021672"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='fec63598679f3f0fe689e462d0b3c45b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1021672"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91905" title="Codeforces Round #727 (Div. 2, по Всероссийской олимпиаде имени Келдыша) [Рейтинговый]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13910:13911" 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/91906" title="tutorial" target="_blank">tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13923" 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/1539">Задачи</a></li> <li><a href="/contest/1539/submit">Отослать</a></li> <li><a href="/contest/1539/my">Мои посылки</a></li> <li><a href="/contest/1539/status">Статус</a></li> <li><a href="/contest/1539/hacks">Взломы</a></li> <li><a href="/contest/1539/room/1">Комната</a></li> <li><a href="/contest/1539/standings">Положение</a></li> <li><a href="/contest/1539/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_1c4f5970113f5b0adad8993d0b2d5bf3d3fb45d4"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$. Уровень знаний $$$i$$$-го ученика равен $$$a_i$$$. Всех учеников нужно распределить на <span class="tex-font-style-it">стабильные группы</span>. Группа называется <span class="tex-font-style-it">стабильной</span>, если после сортировки всех учеников группы в порядке возрастания их уровня знаний у любых двух подряд идущих учеников разница уровня знаний не превосходит $$$x$$$.</p><p>Например, при $$$x = 4$$$ группа с уровнями знаний $$$[1, 10, 8, 4, 4]$$$ является стабильной (потому что $$$4 - 1 \le x$$$, $$$4 - 4 \le x$$$, $$$8 - 4 \le x$$$, $$$10 - 8 \le x$$$), а группа с уровнями $$$[2, 10, 10, 7]$$$ не является стабильной ($$$7 - 2 = 5 &gt; x$$$).</p><p>Преподаватели — достаточно находчивые люди, поэтому в дополнение к $$$n$$$ имеющимся ученикам они могут пригласить не более $$$k$$$ дополнительных учеников с <span class="tex-font-style-bf">любым</span> уровнем знаний на выбор преподавателей. Определите минимальное число стабильных групп, на которые можно распределить всех учеников (возможно, пригласив новых учеников).</p><p>Например, если есть два ученика с уровнями знаний $$$1$$$ и $$$5$$$, $$$x = 2$$$, и $$$k \ge 1$$$, то можно пригласить ученика с уровнем знаний $$$3$$$ и определить всех учеников в одну стабильную группу.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся три целых числа $$$n$$$, $$$k$$$, $$$x$$$ ($$$1 \le n \le 200\,000$$$, $$$0 \le k \le 10^{18}$$$, $$$1 \le x \le 10^{18}$$$) — количество учеников, сколько учеников можно пригласить дополнительно и максимальная допустимая разница уровня знаний.</p><p>Во второй строке вводится $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^{18}$$$) — уровни знаний учеников.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В единственной строке выведите одно число — искомое минимальное число стабильных групп, на которое можно разбить учеников.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 8 2 3 1 1 5 8 12 13 20 22 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 13 0 37 20 20 80 70 70 70 420 5 1 5 1 60 90 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере из условия можно пригласить учеников с уровнями знаний, равными $$$2$$$ и $$$11$$$. Тогда учеников можно разделить на следующие стабильные группы: </p><ol> <li> $$$[1, 1, 2, 5, 8, 11, 12, 13]$$$, </li><li> $$$[20, 22]$$$. </li></ol><p>Во втором примере из условия новых учеников приглашать нельзя, поэтому потребуется $$$3$$$ группы: </p><ol> <li> $$$[1, 1, 5, 5, 20, 20]$$$ </li><li> $$$[60, 70, 70, 70, 80, 90]$$$ </li><li> $$$[420]$$$ </li></ol></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c69d180f13ba',t:'MTY5NjY2NzM2MC45MDcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1200"]
https://codeforces.com/blog/entry/91906
<!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="c4ae3f1dbdd3aa7685e27f571fc144d8"/> <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="Codeforces Round #727 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #727 Editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='c4ae3f1dbdd3aa7685e27f571fc144d8'>&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%2F91906">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='c4ae3f1dbdd3aa7685e27f571fc144d8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:31:34</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:31:34</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='c4ae3f1dbdd3aa7685e27f571fc144d8'/> <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="92516"> <div class="title"> <a href="/blog/entry/91906"> <p>Codeforces Round #727 Editorial</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="Jun/18/2021 00:11">2 years ago</span>, translation, <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/1539/problem/A" title="Codeforces Round 727 (Div. 2)">1539A - Contest Start</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/1539/problem/B" title="Codeforces Round 727 (Div. 2)">1539B - Love Song</a> was authored by jury and prepared by <a class="rated-user user-red" href="/profile/talant" title="Grandmaster talant">talant</a></p><p><a href="/contest/1539/problem/C" title="Codeforces Round 727 (Div. 2)">1539C - Stable Groups</a> was authored by <a class="rated-user user-orange" href="/profile/Artyom123" title="International Master Artyom123">Artyom123</a> and prepared by <a class="rated-user user-orange" href="/profile/Artyom123" title="International Master Artyom123">Artyom123</a> and <a class="rated-user user-blue" href="/profile/shishyando" title="Expert shishyando">shishyando</a></p><p><a href="/contest/1539/problem/D" title="Codeforces Round 727 (Div. 2)">1539D - PriceFixed</a> was authored by Helen Andreeva and prepared by <a class="rated-user user-red" href="/profile/Siberian" title="Grandmaster Siberian">Siberian</a></p><p><a href="/contest/1539/problem/E" title="Codeforces Round 727 (Div. 2)">1539E - Game with Cards</a> was authored and prepared by <a class="rated-user user-orange" href="/profile/TeaTime" title="Master TeaTime">TeaTime</a></p><p><a href="/contest/1539/problem/F" title="Codeforces Round 727 (Div. 2)">1539F - Strange Array</a> was authored and prepared by <a class="rated-user user-orange" href="/profile/Tikhon228" title="Master Tikhon228">Tikhon228</a></p> <div class="problemTutorial" problemcode="1539A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539C">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539D">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539E">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539F">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/1539" class="notice" style="text-decoration: none;">Codeforces Round 727 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-42191-92516").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: "91906", 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> <span style="padding: 0 0.35em;"> <a href="/search?query=%23727" class="tag notice" style="text-decoration: none;">#727</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-92516"><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'>+79</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-92516"><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="Jun/18/2021 00:11">2 years ago</span> </li> <li> <a href="/blog/entry/91906#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/91906#comments"> 116 </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="100475"> <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 (81)</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="807107" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hhoppitree" style="position: relative;"> <img src='https://userpic.codeforces.org/1366950/avatar/874468310bfb5ee5.jpg'/> </a> <div><a href="/profile/hhoppitree" title="Grandmaster hhoppitree" class="rated-user user-red">hhoppitree</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 01:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807107" href="?#comment-807107" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807107" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1366950" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807107"> <div class="moveup"> <div class="ttypography"><p>A great competition with hacking :)</p></div> </div> </div> <div class="reply info"> <a class="comment-807107 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807107 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807107"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807116" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iLoveIOI" style="position: relative;"> <img src='https://userpic.codeforces.org/483613/avatar/19b4d34a35f1e022.jpg'/> </a> <div><a href="/profile/iLoveIOI" title="Master iLoveIOI" class="rated-user user-orange">iLoveIOI</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 03:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807116" href="?#comment-807116" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807116" class="CommentVoteFrame" data-commentRating="34" data-commentUserId="483613" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+34</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807116"> <div class="moveup"> <div class="ttypography"><p>Can someone explain one of the multiset solutions to E? Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-807116 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807116 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807116"> <li> <div class="comment"> <table class="comment-table" commentId="807421" commentParentId="807116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lazywitt" style="position: relative;"> <img src='https://userpic.codeforces.org/995139/avatar/e4276e734c1b167e.jpg'/> </a> <div><a href="/profile/lazywitt" title="Pupil lazywitt" class="rated-user user-green">lazywitt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 21:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807421" href="?#comment-807421" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807116" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807421" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="995139" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807421"> <div class="moveup"> <div class="ttypography"><p>Can you show any multiset solutions which passed ? </p></div> </div> </div> <div class="reply info"> <a class="comment-807421 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807421 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807421"> <li> <div class="comment"> <table class="comment-table" commentId="807448" commentParentId="807421"> <tr> <td class="left"> <div style="position: absolute; left: 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/iLoveIOI" style="position: relative;"> <img src='https://userpic.codeforces.org/483613/avatar/19b4d34a35f1e022.jpg'/> </a> <div><a href="/profile/iLoveIOI" title="Master iLoveIOI" class="rated-user user-orange">iLoveIOI</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 04:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807448" href="?#comment-807448" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807421" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807448" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="483613" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807448"> <div class="moveup"> <div class="ttypography"><p>For example, <a href="https://codeforces.com/contest/1539/submission/120110352">this</a> and <a href="https://codeforces.com/contest/1539/submission/120092916">this</a>. </p></div> </div> </div> <div class="reply info"> <a class="comment-807448 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807448 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807448"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807484" commentParentId="807116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lucaperju" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lucaperju" title="International Grandmaster lucaperju" class="rated-user user-red">lucaperju</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 09:45">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807484" href="?#comment-807484" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807116" style="font-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="807484" 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="807484" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="627011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807484"> <div class="moveup"> <div class="ttypography"><p>Consider dpL[i][j] (different from the one from the editorial) as equal to 1 if it's possible to take the first i cards, ith one in the left hand, and j being the last card we took in the right hand (j&lt;i). And, dpR[j][i] as equal to 1 if it's possible to take the first i cards, last one in the right hand, and j being the last card we took in the left hand. then, instead of storing the whole array, let L[i] be a set (or multiset) of pairs of &lt;k[j],j&gt; such that dpL[i][j] is 1, (and the same for R[i]). Now, if we're at step i and know L[i] and R[i], let's try to compute L[i+1] and R[i+1]: Let's focus on computing L[i+1], for R[i+1] it's similar: if (i+1)th card can't go in the left hand, then L[i+1] will be empty, let's assume it can go there. Let's also assume that the (i+1)th right hand can take any card, we'll fix that later. Then, first of all, if the set R[i] is not empty, we should add the pair &lt;k[i],i&gt; to L[i+1], that's because we can go from having the cards from (j, i) to (i+1, i) by taking the i+1th card in the left hand. And, let's also add to L[i+1] all the pairs from L[i], because we can get those by going from (i, j) to (i+1, j). Now, I assumed that the (i+1)th right hand can take any card, while in reality it can only take those whose k is between ar[i+1] and br[i+1]. So, let's erase from L[i+1] the pairs that are not valid. Since it's a set, we can just erase the smallest card values and the highest card values from the set which are not in the interval. This might seem like it's too slow, but it's actually amortized, because at each step, we only add at most one new pair to the set ( the pair &lt;k[i], i&gt; ), and delete some of the pairs which aren't valid. I'm not sure if I explained this very well, I hope it's clear.</p></div> </div> </div> <div class="reply info"> <a class="comment-807484 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807484 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807484"> <li> <div class="comment"> <table class="comment-table" commentId="807490" commentParentId="807484"> <tr> <td class="left"> <div style="position: absolute; left: 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/iLoveIOI" style="position: relative;"> <img src='https://userpic.codeforces.org/483613/avatar/19b4d34a35f1e022.jpg'/> </a> <div><a href="/profile/iLoveIOI" title="Master iLoveIOI" class="rated-user user-orange">iLoveIOI</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 10:26">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807490" href="?#comment-807490" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807484" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807490" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="483613" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807490"> <div class="moveup"> <div class="ttypography"><p>Ah, I see thanks a lot! It was very clear :)</p></div> </div> </div> <div class="reply info"> <a class="comment-807490 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807490 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807490"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807916" commentParentId="807484"> <tr> <td class="left"> <div style="position: absolute; left: 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/Mrajaryan" style="position: relative;"> <img src='https://userpic.codeforces.org/1377953/avatar/e904b3a3a2eac1ad.jpg'/> </a> <div><a href="/profile/Mrajaryan" title="Newbie Mrajaryan" class="rated-user user-gray">Mrajaryan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 13:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807916" href="?#comment-807916" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807484" style="font-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="807916" 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="807916" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1377953" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807916"> <div class="moveup"> <div class="ttypography"><p>Thanks for explanation. But I can't understand why I should use dp? Can you please give some idea on this ? Or just tell me the naive approach by which i can solve the problem? Like naive dp approach</p></div> </div> </div> <div class="reply info"> <a class="comment-807916 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807916 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807916"> <li> <div class="comment"> <table class="comment-table" commentId="807995" commentParentId="807916"> <tr> <td class="left"> <div style="position: absolute; left: 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/lucaperju" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lucaperju" title="International Grandmaster lucaperju" class="rated-user user-red">lucaperju</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 17:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807995" href="?#comment-807995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807916" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807995" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="627011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807995"> <div class="moveup"> <div class="ttypography"><p>A naive dp approach using the same dp I described above would be: dpL[i][j] (j&lt;i) is true if, obviously, ith card can stay in the left hand (at step i), and jth card can stay in the right hand (at step i), and either:</p> <ul> <li><p>j &lt; (i-1), and dpL[i-1][j] is true</p></li> <li><p>OR j == (i-1), and there exists such k &lt; (i-1) so that dpR[k][i-1] is true</p></li> </ul><p>And similarly for dpR. After calculating this, you can easily recreate the solution from right to left.</p></div> </div> </div> <div class="reply info"> <a class="comment-807995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807995"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="810899" commentParentId="807484"> <tr> <td class="left"> <div style="position: absolute; left: 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/vishaaaal" style="position: relative;"> <img src='https://userpic.codeforces.org/1443354/avatar/25a2dd924894eeeb.jpg'/> </a> <div><a href="/profile/vishaaaal" title="Expert vishaaaal" class="rated-user user-blue">vishaaaal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/02/2021 20:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810899" href="?#comment-810899" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807484" style="font-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="810899" 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="810899" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1443354" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-810899"> <div class="moveup"> <div class="ttypography"><p>How will the following be represented according to these dp states?</p><p>We can pick all the cards upto the ith card in the left hand but none of them in the right hand (in other words, all the queries are answered on the left hand upto the ith card). </p><p>This would imply that there is no j such that dpL[i][j] is 1. But still we can answer all the queries upto the ith card.</p><p>Edit: I thought a lil bit about it and I think we can use 0 as a dummy card (which basically means, by default we'll have 0 as a card in right hand if we don't pick any card in it). And yess, AC. Great explanation OFZ.</p></div> </div> </div> <div class="reply info"> <a class="comment-810899 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810899 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810899"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807117" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Acfboy" style="position: relative;"> <img src='https://userpic.codeforces.org/873793/avatar/146c53315bccb6e9.jpg'/> </a> <div><a href="/profile/Acfboy" title="Master Acfboy" class="rated-user user-orange">Acfboy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 03:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807117" href="?#comment-807117" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807117" class="CommentVoteFrame" data-commentRating="61" data-commentUserId="873793" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+61</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807117"> <div class="moveup"> <div class="ttypography"><p>Nice problems, but the gap between problem ABCD and EF seems too large.</p></div> </div> </div> <div class="reply info"> <a class="comment-807117 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807117 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807117"> <li> <div class="comment"> <table class="comment-table" commentId="807121" commentParentId="807117"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807121" href="?#comment-807121" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807117" style="font-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="807121" 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="807121" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807121"> <div class="moveup"> <div class="ttypography"><p>I think there is a mistake in the editorial of the Problem F.</p><p>The editorial said if the $$$a_i$$$ is less than or equal to the median element then $$$ans = \left\lfloor\dfrac{cnt_R+cnt_M-cnt_L+1}{2} \right\rfloor$$$, but if I have an array that is $$$[1, 2, 3, 4, 4, 6]$$$, the ans of the number $$$4$$$ should be 1, and if you use the formula mentioned above, you may get a wrong answer 0.</p><p>Could anyone tell me the correct formula?</p></div> </div> </div> <div class="reply info"> <a class="comment-807121 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807121 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807121"> <li> <div class="comment"> <table class="comment-table" commentId="807156" commentParentId="807121"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807156" href="?#comment-807156" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807121" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807156" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807156"> <div class="moveup"> <div class="ttypography"><p>The formula is correct, but it's for when the element come to the left of median. When element comes to right of median, other formula should be used which should give you 1. That's why we should take maximum from left &amp; right.</p></div> </div> </div> <div class="reply info"> <a class="comment-807156 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807156 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807156"> <li> <div class="comment"> <table class="comment-table" commentId="807196" commentParentId="807156"> <tr> <td class="left"> <div style="position: absolute; left: 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/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807196" href="?#comment-807196" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807156" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807196" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807196"> <div class="moveup"> <div class="ttypography"><p>Thank you very much. You're right and I have solved this problem by using two distinct formulas. </p></div> </div> </div> <div class="reply info"> <a class="comment-807196 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807196 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807196"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807159" commentParentId="807121"> <tr> <td class="left"> <div style="position: absolute; left: 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/Ka1hatsu" style="position: relative;"> <img src='https://userpic.codeforces.org/761494/avatar/5d5b8ffd577a29a8.jpg'/> </a> <div><a href="/profile/Ka1hatsu" title="Pupil Ka1hatsu" class="rated-user user-green">Ka1hatsu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807159" href="?#comment-807159" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807121" style="font-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="807159" 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="807159" class="CommentVoteFrame" data-commentRating="-6" data-commentUserId="761494" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807159"> <div class="moveup"> <div class="ttypography"><p>sorry</p></div> </div> </div> <div class="reply info"> <a class="comment-807159 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807159 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807159"> <li> <div class="comment"> <table class="comment-table" commentId="807192" commentParentId="807159"> <tr> <td class="left"> <div style="position: absolute; left: 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/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807192" href="?#comment-807192" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807159" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807192" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807192"> <div class="moveup"> <div class="ttypography"><p>I'm sorry but the median number is 4 according to the Problem F.</p></div> </div> </div> <div class="reply info"> <a class="comment-807192 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807192 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807192"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807120" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/highighiq" style="position: relative;"> <img src='https://userpic.codeforces.org/1420719/avatar/97be0e366e499727.jpg'/> </a> <div><a href="/profile/highighiq" title="Master highighiq" class="rated-user user-orange">highighiq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807120" href="?#comment-807120" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807120" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="1420719" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807120"> <div class="moveup"> <div class="ttypography"><p>Good problems!(But E,F is too difficult!) And I get to expert!</p></div> </div> </div> <div class="reply info"> <a class="comment-807120 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807120 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807120"> <li> <div class="comment"> <table class="comment-table" commentId="807122" commentParentId="807120"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807122" href="?#comment-807122" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807120" style="font-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="807122" 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="807122" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807122"> <div class="moveup"> <div class="ttypography"><p>Congratulations!</p></div> </div> </div> <div class="reply info"> <a class="comment-807122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807122"> <li> <div class="comment"> <table class="comment-table" commentId="807125" commentParentId="807122"> <tr> <td class="left"> <div style="position: absolute; left: 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/highighiq" style="position: relative;"> <img src='https://userpic.codeforces.org/1420719/avatar/97be0e366e499727.jpg'/> </a> <div><a href="/profile/highighiq" title="Master highighiq" class="rated-user user-orange">highighiq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:12">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807125" href="?#comment-807125" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807122" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807125" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1420719" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807125"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-807125 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807125 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807125"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807124" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hithu" style="position: relative;"> <img src='https://userpic.codeforces.org/202138/avatar/c537257b9e17f402.jpg'/> </a> <div><a href="/profile/hithu" title="Pupil hithu" class="rated-user user-green">hithu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:09">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807124" href="?#comment-807124" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="202138" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807124"> <div class="moveup"> <div class="ttypography"><p>Still don't understand editorial of D, can anybody explain the two pointer technique?</p></div> </div> </div> <div class="reply info"> <a class="comment-807124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807124"> <li> <div class="comment"> <table class="comment-table" commentId="807128" commentParentId="807124"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Enigma20" style="position: relative;"> <img src='https://userpic.codeforces.org/1301418/avatar/3ba73a2cb1eeb8ef.jpg'/> </a> <div><a href="/profile/Enigma20" title="Expert Enigma20" class="rated-user user-blue">Enigma20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807128" href="?#comment-807128" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807124" style="font-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="807128" 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="807128" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="1301418" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807128"> <div class="moveup"> <div class="ttypography"><p>First we sort the array according to increasing order of $$$b_i$$$. Now, we maintain 2 pointers one at the start of the array(say $$$i$$$) and other one at the end(say $$$j$$$). Also, let's maintain two variables $$$cur$$$(stores number of products already taken), $$$ans$$$(stores the required answer).</p><p>Now, we run a loop until $$$i\leq j$$$.</p><p>If $$$cur\geq b_i$$$, there is no point to leave this product, so we buy all $$$a_i$$$ products with 50% discount and update our $$$cur$$$ and $$$ans$$$.</p><p>If $$$cur\lt b_i$$$, then we start from second pointer i.e. $$$j$$$ and keep taking $$$min(b_i-cur,a_j)$$$ products for 2 rubles, if $$$cur\lt b_j$$$, otherwise for 1 ruble. We stop once we have $$$cur\geq b_i$$$. Update $$$cur,ans,a_j$$$ accordingly. If $$$a_j=0$$$, decrement $$$j$$$.</p><p><a href="https://codeforces.com/contest/1539/submission/120108298">My submission</a></p><p>In this submission, I ran a loop until $$$i\lt j$$$ and checked $$$i=j$$$ condition separately but that isn't necessary.</p></div> </div> </div> <div class="reply info"> <a class="comment-807128 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807128 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807128"> <li> <div class="comment"> <table class="comment-table" commentId="807155" commentParentId="807128"> <tr> <td class="left"> <div style="position: absolute; left: 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/crozzhtt" style="position: relative;"> <img src='https://userpic.codeforces.org/1592985/avatar/ea9a2bfb02b015fb.jpg'/> </a> <div><a href="/profile/crozzhtt" title="Newbie crozzhtt" class="rated-user user-gray">crozzhtt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807155" href="?#comment-807155" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807128" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807155" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1592985" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807155"> <div class="moveup"> <div class="ttypography"><p>but when cur &lt; bi I wonder if I can choose to continue buying (i-1)th product for 1 ruble or buying j-th product for 2 rubles. Will the 2nd option be more optimal than the 1st option?</p></div> </div> </div> <div class="reply info"> <a class="comment-807155 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807155 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807155"> <li> <div class="comment"> <table class="comment-table" commentId="807161" commentParentId="807155"> <tr> <td class="left"> <div style="position: absolute; left: 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/Enigma20" style="position: relative;"> <img src='https://userpic.codeforces.org/1301418/avatar/3ba73a2cb1eeb8ef.jpg'/> </a> <div><a href="/profile/Enigma20" title="Expert Enigma20" class="rated-user user-blue">Enigma20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807161" href="?#comment-807161" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807155" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807161" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1301418" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807161"> <div class="moveup"> <div class="ttypography"><p>Yes, second case will be optimal. Look at it this way, you have to buy as many products for 50% discount as possible. Now we know $$$i^{th}$$$ product has smaller $$$b_i$$$, so the condition for discount of this product will be fulfilled by taking lesser number of products for 2 rubles. Also it may happen that after taking $$$i^{th}$$$ product for 50% discount, products with higher $$$b_i$$$ can be taken for 50% discount without additional cost of 2 rubles. So, 2nd case will be optimal.</p></div> </div> </div> <div class="reply info"> <a class="comment-807161 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807161 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807161"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807130" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/avdp" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/avdp" title="Newbie avdp" class="rated-user user-gray">avdp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807130" href="?#comment-807130" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807130" class="CommentVoteFrame" data-commentRating="97" data-commentUserId="1840186" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+97</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807130"> <div class="moveup"> <div class="ttypography"><p><img alt=" " src="/predownloaded/0d/c4/0dc4ee86562ac0c8d31bcf482bed113f62f1fda1.jpg" style="max-width: 100.0%;max-height: 100.0%;" /></p><p><a class="rated-user user-red" href="/profile/galen_colin" title="Международный гроссмейстер galen_colin">galen_colin</a> <strong>too</strong></p></div> </div> </div> <div class="reply info"> <a class="comment-807130 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807130 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807130"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807132" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Atomsky" style="position: relative;"> <img src='https://userpic.codeforces.org/336914/avatar/2c5685b756a63503.jpg'/> </a> <div><a href="/profile/Atomsky" title="Newbie Atomsky" class="rated-user user-gray">Atomsky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807132" href="?#comment-807132" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807132" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="336914" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807132"> <div class="moveup"> <div class="ttypography"><p>I submitted <a href="/contest/1539/submission/120147862" title="Посылка 120147862 от Atomsky">120147862</a> for Problem-C. It gave a wrong result on test 62 in GNU C++17. When I submitted the same code in C++11, it was accepted (<a href="/contest/1539/submission/120149347" title="Посылка 120149347 от Atomsky">120149347</a>).</p><p>It would be helpful if anyone tells me what went wrong in my code.</p></div> </div> </div> <div class="reply info"> <a class="comment-807132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807132"> <li> <div class="comment"> <table class="comment-table" commentId="807136" commentParentId="807132"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/avdp" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/avdp" title="Newbie avdp" class="rated-user user-gray">avdp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 06:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807136" href="?#comment-807136" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807136" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1840186" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807136"> <div class="moveup"> <div class="ttypography"><p>Hey there, It is because of precision error differences in C++11 and C++17, So it is always advised to use <strong>long double</strong> instead of <strong>double</strong>. You will get AC in both versions with <strong>long double</strong>.</p></div> </div> </div> <div class="reply info"> <a class="comment-807136 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807136 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807136"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807165" commentParentId="807132"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/maskman_lucifer" style="position: relative;"> <img src='https://userpic.codeforces.org/1453975/avatar/e7e8769e223b3ab9.jpg'/> </a> <div><a href="/profile/maskman_lucifer" title="Pupil maskman_lucifer" class="rated-user user-green">maskman_lucifer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807165" href="?#comment-807165" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807165" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1453975" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807165"> <div class="moveup"> <div class="ttypography"><p>In these cases use this (val + d-1 )/ d instead of some ceil on double (Try to avoid doubles if you can do the same with int (precision issue)).<br /> In your case foo[i] = (jar[i] — jar[i-1] + x-1)/x will be good to go.</p></div> </div> </div> <div class="reply info"> <a class="comment-807165 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807165 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807165"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807144" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/UpMing" style="position: relative;"> <img src='https://userpic.codeforces.org/1424136/avatar/2e9bc60a07619853.jpg'/> </a> <div><a href="/profile/UpMing" title="Candidate Master UpMing" class="rated-user user-violet">UpMing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 06:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807144" href="?#comment-807144" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807144" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="1424136" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807144"> <div class="moveup"> <div class="ttypography"><p>The difficulty range is very large,</p><p>For example, D through E</p></div> </div> </div> <div class="reply info"> <a class="comment-807144 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807144 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807144"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807157" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hurt_FOR_heart" style="position: relative;"> <img src='https://userpic.codeforces.org/1445761/avatar/4bd86d3c8cfb747a.jpg'/> </a> <div><a href="/profile/hurt_FOR_heart" title="Candidate Master hurt_FOR_heart" class="rated-user user-violet">hurt_FOR_heart</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807157" href="?#comment-807157" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807157" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="1445761" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807157"> <div class="moveup"> <div class="ttypography"><p>In problem E, i thing that it's hard to come up with such dp state. Does anyone have a more natural idea for this problem ? </p></div> </div> </div> <div class="reply info"> <a class="comment-807157 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807157 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807157"> <li> <div class="comment"> <table class="comment-table" commentId="807183" commentParentId="807157"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/andr14142" style="position: relative;"> <img src='https://userpic.codeforces.org/620444/avatar/368d81a28bf4f89b.jpg'/> </a> <div><a href="/profile/andr14142" title="Pupil andr14142" class="rated-user user-green">andr14142</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 08:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807183" href="?#comment-807183" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807157" style="font-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="807183" revisionCount="7" revision="7"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">7</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="807183" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="620444" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807183"> <div class="moveup"> <div class="ttypography"><p>A more natural idea is to calculate limits for both hands from the end.<br /> Last move has no limits. The range for both hands of last move is from 0 to m inclusive.<br /> For the previous move check cases. Initially limits impossible m &lt; k &lt; 0.<br /> If you can take the card into left hand, then check, could you keep your right hand for the next move? If left card may be kept, limits for the right hand are the current limits for right hand. Otherwise right hand must be kept for the next move, so intersect current limits for right hand with limits for next move.<br /> The same for the right hand.<br /> Finally we check limits for initial situation, is pair (0,0) allowed.</p></div> </div> </div> <div class="reply info"> <a class="comment-807183 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807183 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807183"> <li> <div class="comment"> <table class="comment-table" commentId="807186" commentParentId="807183"> <tr> <td class="left"> <div style="position: absolute; left: 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/rag-hav" style="position: relative;"> <img src='https://userpic.codeforces.org/1809311/avatar/8456dc0c30997ac5.jpg'/> </a> <div><a href="/profile/rag-hav" title="Expert rag-hav" class="rated-user user-blue">rag-hav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807186" href="?#comment-807186" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807183" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807186" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1809311" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807186"> <div class="moveup"> <div class="ttypography"><p>Isn't that exponential complexity? (two choices in every move)</p></div> </div> </div> <div class="reply info"> <a class="comment-807186 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807186 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807186"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807171" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/deletha" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/deletha" title="Pupil deletha" class="rated-user user-green">deletha</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807171" href="?#comment-807171" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807171" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1806788" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807171"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1539/submission/120173484" title="Посылка 120173484 от deletha">120173484</a> I am getting runtime error on test 23 in problem C. Unable to understand if it is due to seg fault or overflows. Can someone pls explain</p></div> </div> </div> <div class="reply info"> <a class="comment-807171 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807171 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807171"> <li> <div class="comment"> <table class="comment-table" commentId="807178" commentParentId="807171"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HowSoOrz" style="position: relative;"> <img src='https://userpic.codeforces.org/1519509/avatar/24d272c5a2a620a1.jpg'/> </a> <div><a href="/profile/HowSoOrz" title="Specialist HowSoOrz" class="rated-user user-cyan">HowSoOrz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 08:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807178" href="?#comment-807178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807171" style="font-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="807178" 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="807178" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1519509" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807178"> <div class="moveup"> <div class="ttypography"><p>Just return when the valid array size is 0. You cant use binary search when the size of the valid vector is 0. Reason: v.begin()=points to first element, v.end() points to next element of last ele.</p><p><a href="/contest/1539/submission/120176292" title="Посылка 120176292 от HowSoOrz">120176292</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807178"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807185" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noobKunal" style="position: relative;"> <img src='https://userpic.codeforces.org/1183443/avatar/73aa8f3ddfbcab8a.jpg'/> </a> <div><a href="/profile/noobKunal" title="Expert noobKunal" class="rated-user user-blue">noobKunal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807185" href="?#comment-807185" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807185" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1183443" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807185"> <div class="moveup"> <div class="ttypography"><p>Can anyone check <a href="https://codeforces.com/contest/1539/submission/120132934">my submission</a> for D. Its giving TLE at tc 11 and it seems that its because of initial sorting itself (and not even entering while loop).</p></div> </div> </div> <div class="reply info"> <a class="comment-807185 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807185 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807185"> <li> <div class="comment"> <table class="comment-table" commentId="807194" commentParentId="807185"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/i_aM_SnEhaal" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/i_aM_SnEhaal" title="Pupil i_aM_SnEhaal" class="rated-user user-green">i_aM_SnEhaal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807194" href="?#comment-807194" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807185" style="font-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="807194" 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="807194" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1279863" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807194"> <div class="moveup"> <div class="ttypography"><p>I tried to submit your solution with just by changing the compare function in sort and it worked. <a href="https://codeforces.com/contest/1539/submission/120179243">Here is the submission have a look</a> just compare it with your solution to see the changes I made.The problem was in how you are defining the compare function in sort. What I have understood is &lt;= or &gt;= is slower than &lt; or &gt; which is causing the problem. For more details please go through <a href="https://codeforces.com/blog/entry/70237">this blog</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-807194 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807194 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807194"> <li> <div class="comment"> <table class="comment-table" commentId="807201" commentParentId="807194"> <tr> <td class="left"> <div style="position: absolute; left: 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/noobKunal" style="position: relative;"> <img src='https://userpic.codeforces.org/1183443/avatar/73aa8f3ddfbcab8a.jpg'/> </a> <div><a href="/profile/noobKunal" title="Expert noobKunal" class="rated-user user-blue">noobKunal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807201" href="?#comment-807201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807194" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807201" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1183443" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807201"> <div class="moveup"> <div class="ttypography"><p>Thanks it passed. Wish i've known this before</p></div> </div> </div> <div class="reply info"> <a class="comment-807201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807201"> <li> <div class="comment"> <table class="comment-table" commentId="807205" commentParentId="807201"> <tr> <td class="left"> <div style="position: absolute; left: 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/i_aM_SnEhaal" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/i_aM_SnEhaal" title="Pupil i_aM_SnEhaal" class="rated-user user-green">i_aM_SnEhaal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807205" href="?#comment-807205" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807205" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1279863" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807205"> <div class="moveup"> <div class="ttypography"><p>I also learnt it the hard way. After getting TLE on TC 11 twice during the contest and then submitting the same code in 8 different ways after the contest was able to figure it out. </p></div> </div> </div> <div class="reply info"> <a class="comment-807205 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807205 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807205"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="1035068" commentParentId="807194"> <tr> <td class="left"> <div style="position: absolute; left: 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/BDboy" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BDboy" title="Expert BDboy" class="rated-user user-blue">BDboy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/05/2023 21:16">4 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1035068" href="?#comment-1035068" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807194" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1035068" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2468471" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1035068"> <div class="moveup"> <div class="ttypography"><p>Thanks, I wont be learning this the hard way. :)</p></div> </div> </div> <div class="reply info"> <a class="comment-1035068 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1035068 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1035068"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807188" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vkgainz" style="position: relative;"> <img src='https://userpic.codeforces.org/679880/avatar/f966b85a769e4f5.jpg'/> </a> <div><a href="/profile/vkgainz" title="Grandmaster vkgainz" class="rated-user user-red">vkgainz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:12">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807188" href="?#comment-807188" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807188" class="CommentVoteFrame" data-commentRating="51" data-commentUserId="679880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+51</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807188"> <div class="moveup"> <div class="ttypography"><p>I found D to be a lot easier to think about using binary search (which solves in $$$O(n\log(10^{14}))$$$. Similar to the editorial, sort with respect to $$$b_i$$$. Now, let $$$x$$$ be the number of items with price $$$1$$$ and $$$y$$$ be the number of items with price $$$2$$$. Then, our answer is equal to $$$x + 2 \cdot y = y + \sum_{i = 1} ^ {n} a_i$$$, so it suffices to minimize $$$y$$$.</p><p>Let's binary search on this. Suppose we set $$$y = k$$$. How do we know if this is enough? First we make two simple observations:</p> <ul> <li><p>We buy all $$$k$$$ items at the very beginning.</p></li> <li><p>We buy all $$$k$$$ items from a suffix of the sorted array.</p></li> </ul><p>Why does this work? Well, if you are going to buy $$$k$$$ items of price $$$2$$$, you should do it earlier than later, because then we might have more $$$b_i$$$ opened up that gives us items of price $$$1$$$. Similarly, we should be buying our items from a suffix because that way we can maximize the number of items of price $$$1$$$ we get (and, subsequently, minimize the number of items of price $$$2$$$). </p><p>From here it's simple to solve with binary search. To test $$$y = k$$$, start a counter for the number of items bought and an index at $$$0$$$. While the counter is greater than $$$b_{\text{index}}$$$, add $$$a_{\text{index}}$$$ to the counter (since we're getting all of those for price $$$1$$$) and increment the counter. If $$$k$$$ is enough, then the counter should be $$$\geq$$$ the number of items we have in total.</p><p>This explanation may seem a bit complicated, but the ideas involved are simple to arrive at and the implementation is very clean: <a href="https://codeforces.com/contest/1539/submission/120179122">my submission here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-807188 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807188 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807188"> <li> <div class="comment"> <table class="comment-table" commentId="807238" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ace-in-the-hole" style="position: relative;"> <img src='https://userpic.codeforces.org/725810/avatar/31d6d37857b526e4.jpg'/> </a> <div><a href="/profile/ace-in-the-hole" title="Candidate Master ace-in-the-hole" class="rated-user user-violet">ace-in-the-hole</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 12:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807238" href="?#comment-807238" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807238" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="725810" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807238"> <div class="moveup"> <div class="ttypography"><p>This idea is nice, but it's still not too different from the solution, because we still have to make the observation: buying items with higher b_i is better. I can say, your idea is <strong>not fundamentally different</strong> from the solution's idea. Maybe because this is not a hard problem so we can't see the diversity of the solutions like some others.</p><p>But it sure is a great idea, the thoughts &quot;I should minimize the number of bought items with price 2&quot;, &quot;I can binary search the answer on this&quot;, ... and more, as you explained, are completely natural and can be thought of. Thank you for your contribution!</p></div> </div> </div> <div class="reply info"> <a class="comment-807238 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807238 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807238"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807334" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/faraz16iqbal" style="position: relative;"> <img src='https://userpic.codeforces.org/1534426/avatar/6269999f6a6fd0c7.jpg'/> </a> <div><a href="/profile/faraz16iqbal" title="Expert faraz16iqbal" class="rated-user user-blue">faraz16iqbal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 17:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807334" href="?#comment-807334" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807334" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1534426" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807334"> <div class="moveup"> <div class="ttypography"><p>Thank you, brilliant explanation</p></div> </div> </div> <div class="reply info"> <a class="comment-807334 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807334 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807334"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807893" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeerInForestovo" style="position: relative;"> <img src='https://userpic.codeforces.org/805889/avatar/8210f0230414d9cc.jpg'/> </a> <div><a href="/profile/DeerInForestovo" title="Master DeerInForestovo" class="rated-user user-orange">DeerInForestovo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 12:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807893" href="?#comment-807893" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807893" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="805889" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807893"> <div class="moveup"> <div class="ttypography"><p>Thanks. In your solution, we finally found a proper position where the things before it were 1 and later than it were 2. So, why not check every possible position and keep some useful information? See <a href="https://codeforces.com/contest/1539/submission/120329507">my submission</a>, which is theoretically O(N) if we use radix sort instead of qsort.</p><p>Sorry for my bad English : )</p></div> </div> </div> <div class="reply info"> <a class="comment-807893 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807893 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807893"> <li> <div class="comment"> <table class="comment-table" commentId="807895" commentParentId="807893"> <tr> <td class="left"> <div style="position: absolute; left: 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/DeerInForestovo" style="position: relative;"> <img src='https://userpic.codeforces.org/805889/avatar/8210f0230414d9cc.jpg'/> </a> <div><a href="/profile/DeerInForestovo" title="Master DeerInForestovo" class="rated-user user-orange">DeerInForestovo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 12:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807895" href="?#comment-807895" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807893" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807895" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="805889" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807895"> <div class="moveup"> <div class="ttypography"><p>In my submission, 'Hab' meant 'Had bought'</p></div> </div> </div> <div class="reply info"> <a class="comment-807895 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807895 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807895"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="868233" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yeetholmes619" style="position: relative;"> <img src='https://userpic.codeforces.org/1957631/avatar/1ad3067143e8096e.jpg'/> </a> <div><a href="/profile/yeetholmes619" title="Expert yeetholmes619" class="rated-user user-blue">yeetholmes619</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/17/2021 01:45">22 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-868233" href="?#comment-868233" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="868233" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1957631" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-868233"> <div class="moveup"> <div class="ttypography"><p>I'm sorry for replying to your comment that is 6 months old, but reading this cleared all my doubts and troubles with this problem, I struggled with finding the right train of thought to solve this problem and the way you explained it removed all of my confusion regarding this.</p><p>The two pointer technique althought gives AC, didn't make the underlying idea behind the solution, i.e x+2y will be our minimum cost which can be re-written as ∑ai + y obvious to me, which your approach clearly does. Thanks a lot! your comment not only helped me in this problem but will help me in future problems as well as it gave light to the right mindset while solving the problem :)</p></div> </div> </div> <div class="reply info"> <a class="comment-868233 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-868233 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-868233"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807217" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Delver0227" style="position: relative;"> <img src='https://userpic.codeforces.org/1594171/avatar/5f6e96d412ba3fde.jpg'/> </a> <div><a href="/profile/Delver0227" title="Specialist Delver0227" class="rated-user user-cyan">Delver0227</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 10:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807217" href="?#comment-807217" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807217" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1594171" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807217"> <div class="moveup"> <div class="ttypography"><p>I have a different way of implementing problem D that is more concise. Considering buying items backwards, we want to the last item we buy is the item with the highest discount requirement(which can be achieved). Which means all we need to do is suppose we have already bought all the items and the number of items is $$$num$$$. Sorting $$$b_i$$$ in non-decreasing order, skip the items that are impossible to get a discount on and take $$$num_i = \min(num-b_i,a_i)$$$ as the number of $$$item_i$$$ which we can buy with a discount. Remember to substract $$$num_i$$$ from $$$num$$$. After iterating $$$i$$$ through all the items, the sum of $$$num_i$$$ is the total number of item that we can get a discount on.</p><p>The code goes like this:<a href="https://paste.ubuntu.com/p/8mwW8n2yfQ/">https://paste.ubuntu.com/p/8mwW8n2yfQ/</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807217 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807217 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807217"> <li> <div class="comment"> <table class="comment-table" commentId="809490" commentParentId="807217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Whimpers" style="position: relative;"> <img src='https://userpic.codeforces.org/1507315/avatar/b11dc9bbdf35d8d9.jpg'/> </a> <div><a href="/profile/Whimpers" title="Expert Whimpers" class="rated-user user-blue">Whimpers</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 03:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809490" href="?#comment-809490" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809490" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1507315" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809490"> <div class="moveup"> <div class="ttypography"><p>why does this work? dont 1's also count towards the total items bought. from what i can see from your solution it is just comparing if the number of items left is greater than the b of the current last item, but if there is an item that has a lot more a than it has b, wouldnt it also be useful in increasing the total number bought and thus would have to be used in the total number of items bought?</p></div> </div> </div> <div class="reply info"> <a class="comment-809490 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809490 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809490"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807229" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Samrev" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Samrev" title="Expert Samrev" class="rated-user user-blue">Samrev</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 11:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807229" href="?#comment-807229" style="font-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="807229" 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="807229" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="1932888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807229"> <div class="moveup"> <div class="ttypography"><p>Test:</p> <pre><code>5 3 10 2 12 1 11 3 10 1 8 </code></pre><p>Submission: <a href="/contest/1539/submission/120129309" title="Посылка 120129309 от Kakashi_099">120129309</a></p><p>Output : 20 Correct Output: 19</p><p>This submission is getting accepted but however the above test case shows wrong output. Correct Output should be 19, instead of 20.</p><p><a class="rated-user user-red" href="/profile/talant" title="Гроссмейстер talant">talant</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807229 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807229 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807229"> <li> <div class="comment"> <table class="comment-table" commentId="807256" commentParentId="807229"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/talant" style="position: relative;"> <img src='https://userpic.codeforces.org/1215930/avatar/cc80e217f41ccfb0.jpg'/> </a> <div><a href="/profile/talant" title="Grandmaster talant" class="rated-user user-red">talant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807256" href="?#comment-807256" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807229" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807256" class="CommentVoteFrame" data-commentRating="58" data-commentUserId="1215930" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+58</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807256"> <div class="moveup"> <div class="ttypography"><p>Stop tagging me, this task isn't even mine</p></div> </div> </div> <div class="reply info"> <a class="comment-807256 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807256 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807256"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807232" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Anish_Bashyal" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Anish_Bashyal" title="Pupil Anish_Bashyal" class="rated-user user-green">Anish_Bashyal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 12:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807232" href="?#comment-807232" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807232" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1411502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807232"> <div class="moveup"> <div class="ttypography"><p><strong>Problem D</strong></p><p>Proof that buying more items of some product than needed doesn't make the answer better. Let's suppose we have already achieved an product (say product A) which we can buy at discount. Now consider we have to buy next product (say product B). </p><p><strong>N</strong> be the number of product B we have to buy, and <strong>d</strong> be the total purchases required before discount and <strong>c</strong> be the amount of items we have already purchased. Then, </p><p><strong>Case I (buy more of product A and then B)</strong></p><p>Total cost for buying product B = <strong>(d-c)*1 + (N*1)</strong> = <strong>d-c+N</strong></p><p><strong>Case II (only buying product B)</strong></p><p>Total cost for buying product B = <strong>2 * (d-c) + ( N-( d-c ) )</strong> = <strong>d-c+N</strong> </p><p>So both the cases cost the same. But this is a special scenario. If we had different percentage of discount, then the above cases wouldn't be equal. </p><p>If we say <strong>m</strong> as discount percentage and <strong>x</strong> as normal price then, </p><p><strong>Case I</strong></p><p><em>mx(d-c) + Nmx</em></p><p><strong>Case II</strong></p><p><em>x(d-c) + (N-d+c)mx</em></p><p>Equating both cases, we get <strong>m = 0.5 or 50%</strong>..</p><p>So only when the discount percentage is 50%, buying more of a discounted product or buying only the required quantity of each products doesn't matter. Hence also in this case, doesn't matter.</p><p>Sorry for writing just the obvious algebra but wanted to share anyway :)</p></div> </div> </div> <div class="reply info"> <a class="comment-807232 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807232 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807232"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807240" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hurt_FOR_heart" style="position: relative;"> <img src='https://userpic.codeforces.org/1445761/avatar/4bd86d3c8cfb747a.jpg'/> </a> <div><a href="/profile/hurt_FOR_heart" title="Candidate Master hurt_FOR_heart" class="rated-user user-violet">hurt_FOR_heart</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807240" href="?#comment-807240" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807240" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="1445761" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807240"> <div class="moveup"> <div class="ttypography"><p>in E</p> <ul> <li>Card in query i fits constraints on value written on card in left hand in queries with indexes [i,j).</li> </ul><p>i think it's [i,j] isn't it ? Because we have card in i for query j too </p></div> </div> </div> <div class="reply info"> <a class="comment-807240 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807240 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807240"> <li> <div class="comment"> <table class="comment-table" commentId="807271" commentParentId="807240"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TeaTime" style="position: relative;"> <img src='https://userpic.codeforces.org/1199093/avatar/f1cbbd424f7d3cf7.jpg'/> </a> <div><a href="/profile/TeaTime" title="Master TeaTime" class="rated-user user-orange">TeaTime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:25">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807271" href="?#comment-807271" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807240" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807271" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="1199093" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807271"> <div class="moveup"> <div class="ttypography"><p>It's [i, j) because card j was already taken in right hand.</p></div> </div> </div> <div class="reply info"> <a class="comment-807271 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807271 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807271"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807273" commentParentId="807240"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TeaTime" style="position: relative;"> <img src='https://userpic.codeforces.org/1199093/avatar/f1cbbd424f7d3cf7.jpg'/> </a> <div><a href="/profile/TeaTime" title="Master TeaTime" class="rated-user user-orange">TeaTime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807273" href="?#comment-807273" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807240" style="font-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="807273" 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="807273" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="1199093" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807273"> <div class="moveup"> <div class="ttypography"><p>Oh, you are correct, I mistook it with something else. Thanks for noticing!</p><p>Edit: editorial was fixed.</p></div> </div> </div> <div class="reply info"> <a class="comment-807273 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807273 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807273"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807241" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pucuk16" style="position: relative;"> <img src='https://userpic.codeforces.org/1458650/avatar/a688a695b97d78cb.jpg'/> </a> <div><a href="/profile/pucuk16" title="Newbie pucuk16" class="rated-user user-gray">pucuk16</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807241" href="?#comment-807241" style="font-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="807241" 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="807241" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1458650" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807241"> <div class="moveup"> <div class="ttypography"><p>hai.. where my code gone wrong..? please help me..<br /> for problem C <br /> thx <a href="https://codeforces.com/contest/1539/submission/120116110">code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807241"> <li> <div class="comment"> <table class="comment-table" commentId="807335" commentParentId="807241"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bwxnQAQ" style="position: relative;"> <img src='https://userpic.codeforces.org/1816180/avatar/1179db2c2821d194.jpg'/> </a> <div><a href="/profile/bwxnQAQ" title="Expert bwxnQAQ" class="rated-user user-blue">bwxnQAQ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 17:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807335" href="?#comment-807335" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807241" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807335" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="1816180" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807335"> <div class="moveup"> <div class="ttypography"><p>You should check line 37.You change d continuously without initializing.The d on the right side of each formula in line 37 should be the d in line 32 instead of the last calculated d.</p></div> </div> </div> <div class="reply info"> <a class="comment-807335 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807335 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807335"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807251" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spookywooky" style="position: relative;"> <img src='https://userpic.codeforces.org/872585/avatar/a8efaf71cbe05928.jpg'/><img title='Почетный бейдж за поддержку Codeforces на его 10-летие' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/spookywooky" title="Specialist spookywooky" class="rated-user user-cyan">spookywooky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807251" href="?#comment-807251" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807251" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="872585" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807251"> <div class="moveup"> <div class="ttypography"><p>Explanation to E sounds like it would be possible to explain it in an understandable way.</p></div> </div> </div> <div class="reply info"> <a class="comment-807251 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807251 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807251"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807258" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807258" href="?#comment-807258" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807258" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807258"> <div class="moveup"> <div class="ttypography"><p><strong>If there is an item which costs 1, then we will not make the answer worse by buying this item.</strong></p><p>Why is that? For example, consider a situation where we've already bought all items, except for one, and it costs 2, and to make it cost 1 we need to buy 2 more items. In that case it would be cheaper to buy one left item and spend 2 instead of buing two more random items at cost 1 and finally buing one last item, spending 3 in total.</p></div> </div> </div> <div class="reply info"> <a class="comment-807258 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807258 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807258"> <li> <div class="comment"> <table class="comment-table" commentId="807275" commentParentId="807258"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807275" href="?#comment-807275" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807258" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807275" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807275"> <div class="moveup"> <div class="ttypography"><p>In your example you are explicitly making the cost of that item by buying more products of other items. But the statement means that if by buying other items and within limits i.e. less that $$$a_i$$$, then you should buy the items of cost 1.</p></div> </div> </div> <div class="reply info"> <a class="comment-807275 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807275 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807275"> <li> <div class="comment"> <table class="comment-table" commentId="807277" commentParentId="807275"> <tr> <td class="left"> <div style="position: absolute; left: 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/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:54">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807277" href="?#comment-807277" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807277" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807277"> <div class="moveup"> <div class="ttypography"><p>Thanks, that explains it:)</p></div> </div> </div> <div class="reply info"> <a class="comment-807277 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807277 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807277"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807331" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/NoobCpp" style="position: relative;"> <img src='https://userpic.codeforces.org/1716219/avatar/14a123abec8289d0.jpg'/> </a> <div><a href="/profile/NoobCpp" title="Specialist NoobCpp" class="rated-user user-cyan">NoobCpp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 17:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807331" href="?#comment-807331" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807331" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1716219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807331"> <div class="moveup"> <div class="ttypography"><p>Although E and F was more difficult than the rest, the contest was great. First time reach to Expert!!</p><p>Sr about my bad Eng :p</p></div> </div> </div> <div class="reply info"> <a class="comment-807331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807331"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807364" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/livlyf_168" style="position: relative;"> <img src='https://userpic.codeforces.org/1919608/avatar/cf064edf00e3eea6.jpg'/> </a> <div><a href="/profile/livlyf_168" title="Pupil livlyf_168" class="rated-user user-green">livlyf_168</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807364" href="?#comment-807364" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807364" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1919608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807364"> <div class="moveup"> <div class="ttypography"><p>Hey, can anyone help me with problem C. Don't know why is it giving WA on test 10. Below is my submission — <a href="/contest/1539/submission/120223010" title="Посылка 120223010 от livlyf_168">120223010</a>. I have used the same approach, except that I have taken The number of elements required to fill the gap as floor((d-1)/x). </p></div> </div> </div> <div class="reply info"> <a class="comment-807364 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807364 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807364"> <li> <div class="comment"> <table class="comment-table" commentId="807370" commentParentId="807364"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/itish" style="position: relative;"> <img src='https://userpic.codeforces.org/1589684/avatar/d4fea913edfbab4b.jpg'/> </a> <div><a href="/profile/itish" title="Candidate Master itish" class="rated-user user-violet">itish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807370" href="?#comment-807370" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807364" style="font-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="807370" 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="807370" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1589684" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807370"> <div class="moveup"> <div class="ttypography"><p>Change vector(int)split to vector(llint) split and it gets accepted</p></div> </div> </div> <div class="reply info"> <a class="comment-807370 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807370 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807370"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807374" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hotas" style="position: relative;"> <img src='https://userpic.codeforces.org/1150129/avatar/590cdb757ae4763a.jpg'/> </a> <div><a href="/profile/Hotas" title="Newbie Hotas" class="rated-user user-gray">Hotas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807374" href="?#comment-807374" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807374" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1150129" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807374"> <div class="moveup"> <div class="ttypography"><p>Can anyone tell me where am I doing wrong? I am getting wrong answer on test case 10. Problem C. Submission : <a href="/contest/1539/submission/120227942" title="Посылка 120227942 от Hotas">120227942</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807374 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807374 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807374"> <li> <div class="comment"> <table class="comment-table" commentId="807397" commentParentId="807374"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 20:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807397" href="?#comment-807397" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807374" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807397" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807397"> <div class="moveup"> <div class="ttypography"><p>I think the problem is that you have int[] a instead of ll[] a. Each element can be up to 1e18.</p></div> </div> </div> <div class="reply info"> <a class="comment-807397 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807397 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807397"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807378" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/coderaman327" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/coderaman327" title="Expert coderaman327" class="rated-user user-blue">coderaman327</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807378" href="?#comment-807378" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807378" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="886853" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807378"> <div class="moveup"> <div class="ttypography"><p>Can someone please tell me what my mistake is in problem D? <a href="https://codeforces.com/contest/1539/submission/120100696">My submission</a> Thanks in advance!!</p></div> </div> </div> <div class="reply info"> <a class="comment-807378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807378"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807400" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abyboi" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/abyboi" title="Pupil abyboi" class="rated-user user-green">abyboi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 21:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807400" href="?#comment-807400" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807400" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1833158" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807400"> <div class="moveup"> <div class="ttypography"><p>Can someone help me with Problem D? My submission is</p><p><a href="https://codeforces.com/contest/1539/submission/120232784">https://codeforces.com/contest/1539/submission/120232784</a></p><p>Thanks in advance!</p></div> </div> </div> <div class="reply info"> <a class="comment-807400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807400"> <li> <div class="comment"> <table class="comment-table" commentId="807478" commentParentId="807400"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/andr14142" style="position: relative;"> <img src='https://userpic.codeforces.org/620444/avatar/368d81a28bf4f89b.jpg'/> </a> <div><a href="/profile/andr14142" title="Pupil andr14142" class="rated-user user-green">andr14142</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 09:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807478" href="?#comment-807478" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807400" style="font-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="807478" 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="807478" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="620444" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807478"> <div class="moveup"> <div class="ttypography"><p>Your solution has not correct comparison in the case of whole buying goods without discount:<br /> else if (total_bought + products[j].F &lt; products[i].S)<br /> Correct comparison is:<br /> else if (total_bought + products[j].F &lt;= products[i].S)</p></div> </div> </div> <div class="reply info"> <a class="comment-807478 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807478 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807478"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807520" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Madara_Uzumaki" style="position: relative;"> <img src='https://userpic.codeforces.org/1621901/avatar/28eb09a48344e5fb.jpg'/> </a> <div><a href="/profile/Madara_Uzumaki" title="Newbie Madara_Uzumaki" class="rated-user user-gray">Madara_Uzumaki</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 11:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807520" href="?#comment-807520" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807520" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1621901" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807520"> <div class="moveup"> <div class="ttypography"><p>In <strong>problem</strong> C i ran the code in <strong>PyPy3</strong> the code got <strong>TLE in test case 18</strong> but when I ran the same code in <strong>Python3</strong> the code got <strong>accepted</strong> Can anyone clarify why did that happen?</p></div> </div> </div> <div class="reply info"> <a class="comment-807520 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807520 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807520"> <li> <div class="comment"> <table class="comment-table" commentId="807527" commentParentId="807520"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/casul" style="position: relative;"> <img src='https://userpic.codeforces.org/1690955/avatar/21ae0e21fe431dd7.jpg'/> </a> <div><a href="/profile/casul" title="Specialist casul" class="rated-user user-cyan">casul</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 12:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807527" href="?#comment-807527" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807520" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807527" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1690955" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807527"> <div class="moveup"> <div class="ttypography"><p>You may wanna check out this blog:</p><p><a href="https://codeforces.com/blog/entry/82989">https://codeforces.com/blog/entry/82989</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807527 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807527 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807527"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807629" commentParentId="807520"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aberent" 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/aberent" title="Specialist aberent" class="rated-user user-cyan">aberent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 18:13">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807629" href="?#comment-807629" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807520" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807629" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1157884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807629"> <div class="moveup"> <div class="ttypography"><p>I too got some strange behaviour with PyPy3 with test 18. Every version I tried printed a result and then (after it should have finished), got TLE. I wonder whether there is a bug somewhere here. See <a href="https://codeforces.com/blog/entry/92011">my blog entry</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-807629 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807629 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807629"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807566" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zvsevolod" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/zvsevolod" title="Newbie zvsevolod" class="rated-user user-gray">zvsevolod</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 14:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807566" href="?#comment-807566" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807566" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1271216" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807566"> <div class="moveup"> <div class="ttypography"><p>In problem C Java solution with Long[] array gets accepted, but long[] array solution gets TLE. (16th line in both solutions) </p><p>ACC: <a href="https://codeforces.com/contest/1539/submission/120284760">https://codeforces.com/contest/1539/submission/120284760</a> <br /> TLE: <a href="https://codeforces.com/contest/1539/submission/120284797">https://codeforces.com/contest/1539/submission/120284797</a></p><p>Could someone explain me why reference type works faster than primitive in this example?</p></div> </div> </div> <div class="reply info"> <a class="comment-807566 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807566 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807566"> <li> <div class="comment"> <table class="comment-table" commentId="807620" commentParentId="807566"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aberent" 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/aberent" title="Specialist aberent" class="rated-user user-cyan">aberent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 18:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807620" href="?#comment-807620" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807566" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807620" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1157884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807620"> <div class="moveup"> <div class="ttypography"><p>Apparently Java uses different sorting algorithms for integers (including longs) and objects. The algorithm for integers is generally faster, but its worst case is worse. You might have simply been unlucky. See the implementation notes for the two versions of sort: <a href="https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(long%5B%5D">https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(long%5B%5D</a>) <a href="https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(java.lang.Object%5B%5D">https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(java.lang.Object%5B%5D</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-807620 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807620 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807620"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807726" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/quinoa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/quinoa" title="Expert quinoa" class="rated-user user-blue">quinoa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 23:40">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807726" href="?#comment-807726" style="font-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="807726" 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="807726" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="592293" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807726"> <div class="moveup"> <div class="ttypography"><p>I had a hard time understanding the tutorial for problem E. This is my attempt at making it easier to understand.</p><p><strong>Easier problem: jump game</strong></p><p>Consider <a href="https://leetcode.com/problems/jump-game/">this</a> easier problem: you have an array $$$x$$$ where $$$x[i]$$$ means what the farthest is that you can jump from position $$$i$$$. Is it possible to reach the last element in the array if you start from position 0?</p><p>We can solve it with a DP where $$$dp[i]$$$ = can we reach the end if we start from position i? The solution to the problem is then equal to $$$dp[0]$$$. The transitions are like this: $$$dp[i]$$$ = $$$dp[i + 1]$$$ $$$||$$$ $$$dp[i + 2]$$$ $$$||$$$ ... $$$||$$$ $$$dp[i + x[i]]$$$. There are $$$N$$$ states and the transitions are $$$O(N)$$$ so this runs in $$$O(N^2)$$$.</p><p>We can make every transition $$$O(1)$$$ with a greedy insight. Instead of checking $$$dp[i + 1]$$$, ..., $$$dp[i + x[i]]$$$ we only need to check $$$dp[j]$$$ where $$$j$$$ is the leftmost position from which we can reach the end. The reason this works is that the leftmost position from which we can reach the end has the best probability of being within our jumping range. We can keep track of this leftmost position as we compute each state in a bottom up fashion.</p> <pre><code>int leftmost_possible = N - 1; for (int i = N - 2; i &gt;= 0; --i) { if (leftmost_possible &lt;= i + x[i]) { dp[i] = true; leftmost_possible = i; } } </code></pre><p><strong>Back to problem E</strong></p><p>We can again solve this with an $$$O(N^2)$$$ DP where $$$dp(x, y)$$$ = can we finish if card with index $$$x$$$ is in the left hand, and card with index $$$y$$$ is in the right hand (and we have just answered query $$$max(x, y)$$$). </p><p>We can notice that we can reduce the number of states to $$$N$$$. Because if we are at $$$dp(x, y)$$$ (WLOG $$$x &gt; y$$$) then</p> <ul> <li>either we will keep replacing the card in the left hand until we reach the end</li> <li>or at some point we have to take something in the right hand and we transition to state $$$dp(k, k + 1)$$$</li> </ul><p>So if we are at state (x, y) then in the next step either we are done, or we will transition to $$$dp(k, k + 1)$$$. Therefore (since we start at state $$$dp(0, 1)$$$) we will only visit states of the type $$$dp(k, k + 1)$$$ (and $$$dp(k - 1, k)$$$), and there are only $$$O(N)$$$ of those.</p><p>The transition is now $$$O(N)$$$ because we have to consider every $$$k$$$ such that $$$dp(k, k + 1)$$$ works. But with the same greedy insight as in the jump game problem we can reduce that to $$$O(1)$$$. Again we can store &quot;the leftmost k that works&quot; as we compute the states and therefore we can find the transition in $$$O(1)$$$.</p><p>Now of course in this problem another hard part is to compute the &quot;maximum jump length&quot; at every position. In the jump game problem this was given in the input, whereas here we have to compute it. For sure you can do it in logarithmic time with a segment tree (I saw it in <a href="https://www.youtube.com/watch?v=seaskdKf2sI">Colin Galen's video</a>). But apparently you can also do it in $$$O(1)$$$ since the solution runs in O(N) according to the tutorial. I didn't think about optimizing that part yet.</p></div> </div> </div> <div class="reply info"> <a class="comment-807726 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807726 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807726"> <li> <div class="comment"> <table class="comment-table" commentId="852194" commentParentId="807726"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ahshafi" style="position: relative;"> <img src='https://userpic.codeforces.org/818506/avatar/d65d006cfdce087a.jpg'/> </a> <div><a href="/profile/ahshafi" title="Candidate Master ahshafi" class="rated-user user-violet">ahshafi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/19/2021 17:24">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-852194" href="?#comment-852194" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807726" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="852194" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="818506" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-852194"> <div class="moveup"> <div class="ttypography"><p>me too confused about how to compute maximum jump length in O(1) </p></div> </div> </div> <div class="reply info"> <a class="comment-852194 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-852194 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-852194"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808157" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sg55" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sg55" title="Newbie sg55" class="rated-user user-gray">sg55</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/24/2021 05:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808157" href="?#comment-808157" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808157" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1445980" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808157"> <div class="moveup"> <div class="ttypography"><p>I have used 2 the same method as used by most of the other coders but my code is giving tle. Can please someone look and tell me why it is? <a href="/contest/1539/submission/120407076" title="Посылка 120407076 от sg55">120407076</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808157 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808157 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808157"> <li> <div class="comment"> <table class="comment-table" commentId="808253" commentParentId="808157"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zvsevolod" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/zvsevolod" title="Newbie zvsevolod" class="rated-user user-gray">zvsevolod</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/24/2021 13:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808253" href="?#comment-808253" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808157" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808253" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1271216" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808253"> <div class="moveup"> <div class="ttypography"><p>Try to use Long[] array instead of long[]. Also you may read my comment above.</p></div> </div> </div> <div class="reply info"> <a class="comment-808253 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808253 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808253"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hritik27" style="position: relative;"> <img src='https://userpic.codeforces.org/1232410/avatar/af014e1c10ef2a19.jpg'/> </a> <div><a href="/profile/hritik27" title="Newbie hritik27" class="rated-user user-gray">hritik27</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/24/2021 19:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808320" href="?#comment-808320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808320" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1232410" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808320"> <div class="moveup"> <div class="ttypography"><p>Can someone please help me with problem A?? Can't understand the solution give.</p></div> </div> </div> <div class="reply info"> <a class="comment-808320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808320"> <li> <div class="comment"> <table class="comment-table" commentId="810306" commentParentId="808320"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/songzy12" style="position: relative;"> <img src='https://userpic.codeforces.org/249570/avatar/3c83a5ef255ff4d6.jpg'/> </a> <div><a href="/profile/songzy12" title="Pupil songzy12" class="rated-user user-green">songzy12</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/30/2021 17:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810306" href="?#comment-810306" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808320" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810306" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="249570" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810306"> <div class="moveup"> <div class="ttypography"><p>1. First consider the case where there are infinite participants. Then each participant would be disturbed by $$$t/x$$$ participants following him. </p><p>2. Then consider the case that $$$n$$$ is finite but large enough, then the first participant would be disturbed by $$$t/x$$$, the same for participant 2, ..., until $$$k$$$. </p><p>For the participants beyond k, the number of participants that would disturb them are decreased by 1 each time, i.e., $$$t/x - 1$$$, $$$t/x - 2$$$, until 0 for the last participant.</p><p>There are $$$t/x$$$ numbers from $$$t/x - 1$$$ until 0, thus we know $$$k = n - t/x$$$.</p><p>So the answer would be $$$(n-t/x) * (t/x) + (t/x-1)*(t/x)/2$$$.</p><p>3. The $$$min$$$ and $$$max$$$ in the answer is to solve the case where n is not large enough, i.e., when $$$n &lt; t/x$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-810306 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810306 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810306"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808360" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/augurar" style="position: relative;"> <img src='https://userpic.codeforces.org/391071/avatar/8a814e47f9aacb44.jpg'/> </a> <div><a href="/profile/augurar" title="Expert augurar" class="rated-user user-blue">augurar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 02:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808360" href="?#comment-808360" style="font-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="808360" 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="808360" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="391071" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808360"> <div class="moveup"> <div class="ttypography"><p>I'm glad I didn't participate in this one officially. Problem C was easy but I kept getting a TLE for stupid language-specific reasons:</p> <ul> <li><p>My <a href="https://codeforces.com/contest/1539/submission/120478273">Python solution</a> got TLE on test 18 with PyPy3, but the same code passed with Python 3.</p></li> <li><p>My <a href="https://codeforces.com/contest/1539/submission/120478521">Java solution</a> got TLE on test 61, but passed if I changed <code>long[]</code> to <code>Long[]</code>. (This is kind of my fault for not knowing Java uses a worst-case O(n^2) sort for primitive arrays.)</p></li> <li><p>My <a href="https://codeforces.com/contest/1539/submission/120480356">C++ solution</a> passed with no special optimization.</p></li> </ul><p>In my opinion that's an indication that the time limit is overly strict, especially for an ABC problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-808360 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808360 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808360"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="816645" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/comseung18_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/comseung18_" title="Expert comseung18_" class="rated-user user-blue">comseung18_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/15/2021 09:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-816645" href="?#comment-816645" style="font-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="816645" 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="816645" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275870" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-816645"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1539/submission/122552751" title="Посылка 122552751 от comseung18_">122552751</a> why my solution A is not correct ? ans1 is Editorial solution ans2 is my solution</p><p>I checked my ans2 in many times. but ans1 equals ans2..<br />~~~~~ import random k = int(input()) for _ in range(k): n = random.randint(1,2*1000000000) x = random.randint(1,2*1000000000) t = random.randint(1,2*1000000000) tmp = t//x ans1 = max(0,n-tmp)*tmp + min(n-1,tmp-1)*min(n,tmp)//2 ans2 = tmp*n — tmp*tmp + tmp*n — ((2*n-tmp+1)*tmp)//2 if ans1 != ans2: print(ans1,ans2) ~~~~~</p></div> </div> </div> <div class="reply info"> <a class="comment-816645 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-816645 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-816645"> <li> <div class="comment"> <table class="comment-table" commentId="816647" commentParentId="816645"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/comseung18_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/comseung18_" title="Expert comseung18_" class="rated-user user-blue">comseung18_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/15/2021 09:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-816647" href="?#comment-816647" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-816645" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="816647" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275870" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-816647"> <div class="moveup"> <div class="ttypography"><p>when , t/x &gt; n , ans2 is wrong sorry</p></div> </div> </div> <div class="reply info"> <a class="comment-816647 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-816647 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-816647"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="984743" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PrickyToTheMoon" style="position: relative;"> <img src='https://userpic.codeforces.org/1432360/avatar/422cb9d88c769b8d.jpg'/> </a> <div><a href="/profile/PrickyToTheMoon" title="Pupil PrickyToTheMoon" class="rated-user user-green">PrickyToTheMoon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/24/2022 21:10">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-984743" href="?#comment-984743" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="984743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1432360" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-984743"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1539/submission/186604051" title="Submission 186604051 by PrickyToTheMoon">186604051</a></p><p>Please help. Cannot understand why getting WA on test case 18. My approach matches perfectly with editorial.</p><p>Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-984743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-984743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-984743"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="995447" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mohsina_Shaikh" style="position: relative;"> <img src='https://userpic.codeforces.org/1396580/avatar/6f21616a2d8d578.jpg'/> </a> <div><a href="/profile/Mohsina_Shaikh" title="Newbie Mohsina_Shaikh" class="rated-user user-gray">Mohsina_Shaikh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/25/2023 07:37">8 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-995447" href="?#comment-995447" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="995447" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1396580" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-995447"> <div class="moveup"> <div class="ttypography"><p>can anyone please explain how problem B can be solved using DP.</p></div> </div> </div> <div class="reply info"> <a class="comment-995447 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-995447 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-995447"> </ul> </div> <br/> <div id="editBox-100475" 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 firstPreview100475 = true; var lastPreviewContent100475 = ''; 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=100475] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=100475] 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-92516").click(function () { $.post("/data/topic/vote", {topicId: 92516, _tta: Codeforces.tta(), topicRevisionId: 229854, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-92516").click(function () { $.post("/data/topic/vote", {topicId: 92516, _tta: Codeforces.tta(), topicRevisionId: 229854, 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:33:26</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:'81289365b9230c42',t:'MTY5NjcwNzIwNi44NDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1539D
1539
D
ru
D. PriceFixed
<div class="problem-statement"><div class="header"><div class="title">D. PriceFixed</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Девочка Лена — самая экономная девочка в Москве. Поэтому когда папа поручил ей закупку продуктов для поездки на дачу, она сразу отправилась в самый лучший магазин — «PriceFixed». У этого магазина есть несколько особенностей:</p><ul> <li> В магазине есть бесконечный запас каждого товара. </li><li> Все товары в нем стоят одинаково — ровно $$$2$$$ рубля за единицу товара. </li><li> Для каждого из $$$i$$$ товаров предусмотрена скидка для опытных покупателей: если вы уже приобрели $$$b_i$$$ единиц товаров (<span class="tex-font-style-bf">любого типа</span>, не обязательно типа $$$i$$$), то на все последующие покупки $$$i$$$-го товара будет действовать скидка $$$50\%$$$ (то есть единицу $$$i$$$-го товара можно будет купить за $$$1$$$ рубль!). </li></ul><p>Лене нужно купить $$$n$$$ товаров: $$$i$$$-го товара нужно купить не менее $$$a_i$$$ единиц. Помогите Лене понять, какую минимальную сумму денег ей нужно будет потратить, если она будет выбирать порядок покупки товаров оптимальным образом. Обратите внимание, Лена, если хочет, может купить больше единиц некоторого товара, чем необходимо.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке вводится число $$$n$$$ ($$$1 \leq n \leq 100\,000$$$) — количество различных товаров в списке.</p><p>В следующих $$$n$$$ строках вводятся описания товаров. Каждое описание состоит из двух чисел $$$a_i$$$ и $$$b_i$$$, ($$$1 \leq a_i \leq 10^{14}$$$, $$$1 \leq b_i \leq 10^{14}$$$) — требуемое число единиц $$$i$$$-го товара и сколько единиц товаров нужно купить, чтобы получить скидку на товар $$$i$$$.</p><p>Сумма всех $$$a_i$$$ в тесте не превосходит $$$10^{14}$$$.</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 4 1 3 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 2 7 2 8 1 2 2 4 1 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 12 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере из условия Лена может купить товары в таком порядке:</p><ol> <li> единицу товара $$$3$$$ за $$$2$$$ рубля, </li><li> единицу товара $$$1$$$ за $$$2$$$ рубля </li><li> единицу товара $$$1$$$ за $$$2$$$ рубля, </li><li> единицу товара $$$2$$$ за $$$1$$$ рубль (она может купить его со скидкой, так как уже куплено $$$3$$$ товара), </li><li> единицу товара $$$1$$$ за $$$1$$$ рубль (она может купить его со скидкой, так как уже куплено $$$4$$$ товара). </li></ol><p>Суммарно она потратит $$$8$$$ рублей. Можно показать, что меньше потратить невозможно.</p><p>Во втором примере из условия Лена может купить товары в таком порядке:</p><ol> <li> единицу товара $$$1$$$ за $$$2$$$ рубля, </li><li> две единицы товара $$$2$$$ по $$$2$$$ рубля за каждую, </li><li> единицу товара $$$5$$$ за $$$2$$$ рубля, </li><li> единицу товара $$$3$$$ за $$$1$$$ рубль, </li><li> две единицы товара $$$4$$$ по $$$1$$$ рублю за каждую, </li><li> единицу товара $$$1$$$ за $$$1$$$ рубль. </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="6bbe8a59751ec7a73a9dcd2a4cc7ae6c"/> <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="3b3d6aa18ec7f2c8636f747ba32c1b3c7997564d"/> <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='6bbe8a59751ec7a73a9dcd2a4cc7ae6c'>&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%2F1539%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='6bbe8a59751ec7a73a9dcd2a4cc7ae6c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1539">Codeforces Round 727 (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='6bbe8a59751ec7a73a9dcd2a4cc7ae6c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1539/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='6bbe8a59751ec7a73a9dcd2a4cc7ae6c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1021673"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6bbe8a59751ec7a73a9dcd2a4cc7ae6c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1021673"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91905" title="Codeforces Round #727 (Div. 2, по Всероссийской олимпиаде имени Келдыша) [Рейтинговый]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13910:13911" 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/91906" title="tutorial" target="_blank">tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13923" 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/1539">Задачи</a></li> <li><a href="/contest/1539/submit">Отослать</a></li> <li><a href="/contest/1539/my">Мои посылки</a></li> <li><a href="/contest/1539/status">Статус</a></li> <li><a href="/contest/1539/hacks">Взломы</a></li> <li><a href="/contest/1539/room/1">Комната</a></li> <li><a href="/contest/1539/standings">Положение</a></li> <li><a href="/contest/1539/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_6bb29252e553a51e923880afab4ef8deafb3e21c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. PriceFixed</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Девочка Лена — самая экономная девочка в Москве. Поэтому когда папа поручил ей закупку продуктов для поездки на дачу, она сразу отправилась в самый лучший магазин — «PriceFixed». У этого магазина есть несколько особенностей:</p><ul> <li> В магазине есть бесконечный запас каждого товара. </li><li> Все товары в нем стоят одинаково — ровно $$$2$$$ рубля за единицу товара. </li><li> Для каждого из $$$i$$$ товаров предусмотрена скидка для опытных покупателей: если вы уже приобрели $$$b_i$$$ единиц товаров (<span class="tex-font-style-bf">любого типа</span>, не обязательно типа $$$i$$$), то на все последующие покупки $$$i$$$-го товара будет действовать скидка $$$50\%$$$ (то есть единицу $$$i$$$-го товара можно будет купить за $$$1$$$ рубль!). </li></ul><p>Лене нужно купить $$$n$$$ товаров: $$$i$$$-го товара нужно купить не менее $$$a_i$$$ единиц. Помогите Лене понять, какую минимальную сумму денег ей нужно будет потратить, если она будет выбирать порядок покупки товаров оптимальным образом. Обратите внимание, Лена, если хочет, может купить больше единиц некоторого товара, чем необходимо.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке вводится число $$$n$$$ ($$$1 \leq n \leq 100\,000$$$) — количество различных товаров в списке.</p><p>В следующих $$$n$$$ строках вводятся описания товаров. Каждое описание состоит из двух чисел $$$a_i$$$ и $$$b_i$$$, ($$$1 \leq a_i \leq 10^{14}$$$, $$$1 \leq b_i \leq 10^{14}$$$) — требуемое число единиц $$$i$$$-го товара и сколько единиц товаров нужно купить, чтобы получить скидку на товар $$$i$$$.</p><p>Сумма всех $$$a_i$$$ в тесте не превосходит $$$10^{14}$$$.</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 4 1 3 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 2 7 2 8 1 2 2 4 1 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 12 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере из условия Лена может купить товары в таком порядке:</p><ol> <li> единицу товара $$$3$$$ за $$$2$$$ рубля, </li><li> единицу товара $$$1$$$ за $$$2$$$ рубля </li><li> единицу товара $$$1$$$ за $$$2$$$ рубля, </li><li> единицу товара $$$2$$$ за $$$1$$$ рубль (она может купить его со скидкой, так как уже куплено $$$3$$$ товара), </li><li> единицу товара $$$1$$$ за $$$1$$$ рубль (она может купить его со скидкой, так как уже куплено $$$4$$$ товара). </li></ol><p>Суммарно она потратит $$$8$$$ рублей. Можно показать, что меньше потратить невозможно.</p><p>Во втором примере из условия Лена может купить товары в таком порядке:</p><ol> <li> единицу товара $$$1$$$ за $$$2$$$ рубля, </li><li> две единицы товара $$$2$$$ по $$$2$$$ рубля за каждую, </li><li> единицу товара $$$5$$$ за $$$2$$$ рубля, </li><li> единицу товара $$$3$$$ за $$$1$$$ рубль, </li><li> две единицы товара $$$4$$$ по $$$1$$$ рублю за каждую, </li><li> единицу товара $$$1$$$ за $$$1$$$ рубль. </li></ol><p>Суммарно при таком порядке приобретения товаров Лена потратит $$$12$$$ рублей.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29:22</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c6a559ef7b33',t:'MTY5NjY2NzM2Mi4yNzAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\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", "*1600"]
https://codeforces.com/blog/entry/91906
<!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="c4ae3f1dbdd3aa7685e27f571fc144d8"/> <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="Codeforces Round #727 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #727 Editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='c4ae3f1dbdd3aa7685e27f571fc144d8'>&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%2F91906">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='c4ae3f1dbdd3aa7685e27f571fc144d8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:31:34</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:31:34</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='c4ae3f1dbdd3aa7685e27f571fc144d8'/> <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="92516"> <div class="title"> <a href="/blog/entry/91906"> <p>Codeforces Round #727 Editorial</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="Jun/18/2021 00:11">2 years ago</span>, translation, <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/1539/problem/A" title="Codeforces Round 727 (Div. 2)">1539A - Contest Start</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/1539/problem/B" title="Codeforces Round 727 (Div. 2)">1539B - Love Song</a> was authored by jury and prepared by <a class="rated-user user-red" href="/profile/talant" title="Grandmaster talant">talant</a></p><p><a href="/contest/1539/problem/C" title="Codeforces Round 727 (Div. 2)">1539C - Stable Groups</a> was authored by <a class="rated-user user-orange" href="/profile/Artyom123" title="International Master Artyom123">Artyom123</a> and prepared by <a class="rated-user user-orange" href="/profile/Artyom123" title="International Master Artyom123">Artyom123</a> and <a class="rated-user user-blue" href="/profile/shishyando" title="Expert shishyando">shishyando</a></p><p><a href="/contest/1539/problem/D" title="Codeforces Round 727 (Div. 2)">1539D - PriceFixed</a> was authored by Helen Andreeva and prepared by <a class="rated-user user-red" href="/profile/Siberian" title="Grandmaster Siberian">Siberian</a></p><p><a href="/contest/1539/problem/E" title="Codeforces Round 727 (Div. 2)">1539E - Game with Cards</a> was authored and prepared by <a class="rated-user user-orange" href="/profile/TeaTime" title="Master TeaTime">TeaTime</a></p><p><a href="/contest/1539/problem/F" title="Codeforces Round 727 (Div. 2)">1539F - Strange Array</a> was authored and prepared by <a class="rated-user user-orange" href="/profile/Tikhon228" title="Master Tikhon228">Tikhon228</a></p> <div class="problemTutorial" problemcode="1539A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539C">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539D">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539E">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539F">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/1539" class="notice" style="text-decoration: none;">Codeforces Round 727 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-42191-92516").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: "91906", 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> <span style="padding: 0 0.35em;"> <a href="/search?query=%23727" class="tag notice" style="text-decoration: none;">#727</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-92516"><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'>+79</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-92516"><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="Jun/18/2021 00:11">2 years ago</span> </li> <li> <a href="/blog/entry/91906#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/91906#comments"> 116 </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="100475"> <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 (81)</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="807107" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hhoppitree" style="position: relative;"> <img src='https://userpic.codeforces.org/1366950/avatar/874468310bfb5ee5.jpg'/> </a> <div><a href="/profile/hhoppitree" title="Grandmaster hhoppitree" class="rated-user user-red">hhoppitree</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 01:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807107" href="?#comment-807107" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807107" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1366950" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807107"> <div class="moveup"> <div class="ttypography"><p>A great competition with hacking :)</p></div> </div> </div> <div class="reply info"> <a class="comment-807107 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807107 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807107"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807116" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iLoveIOI" style="position: relative;"> <img src='https://userpic.codeforces.org/483613/avatar/19b4d34a35f1e022.jpg'/> </a> <div><a href="/profile/iLoveIOI" title="Master iLoveIOI" class="rated-user user-orange">iLoveIOI</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 03:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807116" href="?#comment-807116" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807116" class="CommentVoteFrame" data-commentRating="34" data-commentUserId="483613" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+34</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807116"> <div class="moveup"> <div class="ttypography"><p>Can someone explain one of the multiset solutions to E? Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-807116 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807116 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807116"> <li> <div class="comment"> <table class="comment-table" commentId="807421" commentParentId="807116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lazywitt" style="position: relative;"> <img src='https://userpic.codeforces.org/995139/avatar/e4276e734c1b167e.jpg'/> </a> <div><a href="/profile/lazywitt" title="Pupil lazywitt" class="rated-user user-green">lazywitt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 21:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807421" href="?#comment-807421" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807116" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807421" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="995139" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807421"> <div class="moveup"> <div class="ttypography"><p>Can you show any multiset solutions which passed ? </p></div> </div> </div> <div class="reply info"> <a class="comment-807421 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807421 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807421"> <li> <div class="comment"> <table class="comment-table" commentId="807448" commentParentId="807421"> <tr> <td class="left"> <div style="position: absolute; left: 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/iLoveIOI" style="position: relative;"> <img src='https://userpic.codeforces.org/483613/avatar/19b4d34a35f1e022.jpg'/> </a> <div><a href="/profile/iLoveIOI" title="Master iLoveIOI" class="rated-user user-orange">iLoveIOI</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 04:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807448" href="?#comment-807448" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807421" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807448" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="483613" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807448"> <div class="moveup"> <div class="ttypography"><p>For example, <a href="https://codeforces.com/contest/1539/submission/120110352">this</a> and <a href="https://codeforces.com/contest/1539/submission/120092916">this</a>. </p></div> </div> </div> <div class="reply info"> <a class="comment-807448 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807448 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807448"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807484" commentParentId="807116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lucaperju" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lucaperju" title="International Grandmaster lucaperju" class="rated-user user-red">lucaperju</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 09:45">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807484" href="?#comment-807484" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807116" style="font-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="807484" 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="807484" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="627011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807484"> <div class="moveup"> <div class="ttypography"><p>Consider dpL[i][j] (different from the one from the editorial) as equal to 1 if it's possible to take the first i cards, ith one in the left hand, and j being the last card we took in the right hand (j&lt;i). And, dpR[j][i] as equal to 1 if it's possible to take the first i cards, last one in the right hand, and j being the last card we took in the left hand. then, instead of storing the whole array, let L[i] be a set (or multiset) of pairs of &lt;k[j],j&gt; such that dpL[i][j] is 1, (and the same for R[i]). Now, if we're at step i and know L[i] and R[i], let's try to compute L[i+1] and R[i+1]: Let's focus on computing L[i+1], for R[i+1] it's similar: if (i+1)th card can't go in the left hand, then L[i+1] will be empty, let's assume it can go there. Let's also assume that the (i+1)th right hand can take any card, we'll fix that later. Then, first of all, if the set R[i] is not empty, we should add the pair &lt;k[i],i&gt; to L[i+1], that's because we can go from having the cards from (j, i) to (i+1, i) by taking the i+1th card in the left hand. And, let's also add to L[i+1] all the pairs from L[i], because we can get those by going from (i, j) to (i+1, j). Now, I assumed that the (i+1)th right hand can take any card, while in reality it can only take those whose k is between ar[i+1] and br[i+1]. So, let's erase from L[i+1] the pairs that are not valid. Since it's a set, we can just erase the smallest card values and the highest card values from the set which are not in the interval. This might seem like it's too slow, but it's actually amortized, because at each step, we only add at most one new pair to the set ( the pair &lt;k[i], i&gt; ), and delete some of the pairs which aren't valid. I'm not sure if I explained this very well, I hope it's clear.</p></div> </div> </div> <div class="reply info"> <a class="comment-807484 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807484 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807484"> <li> <div class="comment"> <table class="comment-table" commentId="807490" commentParentId="807484"> <tr> <td class="left"> <div style="position: absolute; left: 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/iLoveIOI" style="position: relative;"> <img src='https://userpic.codeforces.org/483613/avatar/19b4d34a35f1e022.jpg'/> </a> <div><a href="/profile/iLoveIOI" title="Master iLoveIOI" class="rated-user user-orange">iLoveIOI</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 10:26">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807490" href="?#comment-807490" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807484" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807490" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="483613" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807490"> <div class="moveup"> <div class="ttypography"><p>Ah, I see thanks a lot! It was very clear :)</p></div> </div> </div> <div class="reply info"> <a class="comment-807490 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807490 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807490"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807916" commentParentId="807484"> <tr> <td class="left"> <div style="position: absolute; left: 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/Mrajaryan" style="position: relative;"> <img src='https://userpic.codeforces.org/1377953/avatar/e904b3a3a2eac1ad.jpg'/> </a> <div><a href="/profile/Mrajaryan" title="Newbie Mrajaryan" class="rated-user user-gray">Mrajaryan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 13:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807916" href="?#comment-807916" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807484" style="font-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="807916" 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="807916" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1377953" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807916"> <div class="moveup"> <div class="ttypography"><p>Thanks for explanation. But I can't understand why I should use dp? Can you please give some idea on this ? Or just tell me the naive approach by which i can solve the problem? Like naive dp approach</p></div> </div> </div> <div class="reply info"> <a class="comment-807916 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807916 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807916"> <li> <div class="comment"> <table class="comment-table" commentId="807995" commentParentId="807916"> <tr> <td class="left"> <div style="position: absolute; left: 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/lucaperju" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lucaperju" title="International Grandmaster lucaperju" class="rated-user user-red">lucaperju</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 17:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807995" href="?#comment-807995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807916" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807995" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="627011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807995"> <div class="moveup"> <div class="ttypography"><p>A naive dp approach using the same dp I described above would be: dpL[i][j] (j&lt;i) is true if, obviously, ith card can stay in the left hand (at step i), and jth card can stay in the right hand (at step i), and either:</p> <ul> <li><p>j &lt; (i-1), and dpL[i-1][j] is true</p></li> <li><p>OR j == (i-1), and there exists such k &lt; (i-1) so that dpR[k][i-1] is true</p></li> </ul><p>And similarly for dpR. After calculating this, you can easily recreate the solution from right to left.</p></div> </div> </div> <div class="reply info"> <a class="comment-807995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807995"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="810899" commentParentId="807484"> <tr> <td class="left"> <div style="position: absolute; left: 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/vishaaaal" style="position: relative;"> <img src='https://userpic.codeforces.org/1443354/avatar/25a2dd924894eeeb.jpg'/> </a> <div><a href="/profile/vishaaaal" title="Expert vishaaaal" class="rated-user user-blue">vishaaaal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/02/2021 20:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810899" href="?#comment-810899" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807484" style="font-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="810899" 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="810899" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1443354" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-810899"> <div class="moveup"> <div class="ttypography"><p>How will the following be represented according to these dp states?</p><p>We can pick all the cards upto the ith card in the left hand but none of them in the right hand (in other words, all the queries are answered on the left hand upto the ith card). </p><p>This would imply that there is no j such that dpL[i][j] is 1. But still we can answer all the queries upto the ith card.</p><p>Edit: I thought a lil bit about it and I think we can use 0 as a dummy card (which basically means, by default we'll have 0 as a card in right hand if we don't pick any card in it). And yess, AC. Great explanation OFZ.</p></div> </div> </div> <div class="reply info"> <a class="comment-810899 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810899 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810899"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807117" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Acfboy" style="position: relative;"> <img src='https://userpic.codeforces.org/873793/avatar/146c53315bccb6e9.jpg'/> </a> <div><a href="/profile/Acfboy" title="Master Acfboy" class="rated-user user-orange">Acfboy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 03:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807117" href="?#comment-807117" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807117" class="CommentVoteFrame" data-commentRating="61" data-commentUserId="873793" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+61</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807117"> <div class="moveup"> <div class="ttypography"><p>Nice problems, but the gap between problem ABCD and EF seems too large.</p></div> </div> </div> <div class="reply info"> <a class="comment-807117 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807117 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807117"> <li> <div class="comment"> <table class="comment-table" commentId="807121" commentParentId="807117"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807121" href="?#comment-807121" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807117" style="font-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="807121" 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="807121" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807121"> <div class="moveup"> <div class="ttypography"><p>I think there is a mistake in the editorial of the Problem F.</p><p>The editorial said if the $$$a_i$$$ is less than or equal to the median element then $$$ans = \left\lfloor\dfrac{cnt_R+cnt_M-cnt_L+1}{2} \right\rfloor$$$, but if I have an array that is $$$[1, 2, 3, 4, 4, 6]$$$, the ans of the number $$$4$$$ should be 1, and if you use the formula mentioned above, you may get a wrong answer 0.</p><p>Could anyone tell me the correct formula?</p></div> </div> </div> <div class="reply info"> <a class="comment-807121 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807121 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807121"> <li> <div class="comment"> <table class="comment-table" commentId="807156" commentParentId="807121"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807156" href="?#comment-807156" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807121" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807156" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807156"> <div class="moveup"> <div class="ttypography"><p>The formula is correct, but it's for when the element come to the left of median. When element comes to right of median, other formula should be used which should give you 1. That's why we should take maximum from left &amp; right.</p></div> </div> </div> <div class="reply info"> <a class="comment-807156 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807156 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807156"> <li> <div class="comment"> <table class="comment-table" commentId="807196" commentParentId="807156"> <tr> <td class="left"> <div style="position: absolute; left: 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/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807196" href="?#comment-807196" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807156" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807196" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807196"> <div class="moveup"> <div class="ttypography"><p>Thank you very much. You're right and I have solved this problem by using two distinct formulas. </p></div> </div> </div> <div class="reply info"> <a class="comment-807196 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807196 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807196"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807159" commentParentId="807121"> <tr> <td class="left"> <div style="position: absolute; left: 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/Ka1hatsu" style="position: relative;"> <img src='https://userpic.codeforces.org/761494/avatar/5d5b8ffd577a29a8.jpg'/> </a> <div><a href="/profile/Ka1hatsu" title="Pupil Ka1hatsu" class="rated-user user-green">Ka1hatsu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807159" href="?#comment-807159" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807121" style="font-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="807159" 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="807159" class="CommentVoteFrame" data-commentRating="-6" data-commentUserId="761494" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807159"> <div class="moveup"> <div class="ttypography"><p>sorry</p></div> </div> </div> <div class="reply info"> <a class="comment-807159 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807159 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807159"> <li> <div class="comment"> <table class="comment-table" commentId="807192" commentParentId="807159"> <tr> <td class="left"> <div style="position: absolute; left: 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/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807192" href="?#comment-807192" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807159" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807192" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807192"> <div class="moveup"> <div class="ttypography"><p>I'm sorry but the median number is 4 according to the Problem F.</p></div> </div> </div> <div class="reply info"> <a class="comment-807192 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807192 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807192"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807120" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/highighiq" style="position: relative;"> <img src='https://userpic.codeforces.org/1420719/avatar/97be0e366e499727.jpg'/> </a> <div><a href="/profile/highighiq" title="Master highighiq" class="rated-user user-orange">highighiq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807120" href="?#comment-807120" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807120" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="1420719" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807120"> <div class="moveup"> <div class="ttypography"><p>Good problems!(But E,F is too difficult!) And I get to expert!</p></div> </div> </div> <div class="reply info"> <a class="comment-807120 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807120 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807120"> <li> <div class="comment"> <table class="comment-table" commentId="807122" commentParentId="807120"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807122" href="?#comment-807122" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807120" style="font-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="807122" 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="807122" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807122"> <div class="moveup"> <div class="ttypography"><p>Congratulations!</p></div> </div> </div> <div class="reply info"> <a class="comment-807122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807122"> <li> <div class="comment"> <table class="comment-table" commentId="807125" commentParentId="807122"> <tr> <td class="left"> <div style="position: absolute; left: 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/highighiq" style="position: relative;"> <img src='https://userpic.codeforces.org/1420719/avatar/97be0e366e499727.jpg'/> </a> <div><a href="/profile/highighiq" title="Master highighiq" class="rated-user user-orange">highighiq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:12">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807125" href="?#comment-807125" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807122" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807125" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1420719" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807125"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-807125 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807125 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807125"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807124" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hithu" style="position: relative;"> <img src='https://userpic.codeforces.org/202138/avatar/c537257b9e17f402.jpg'/> </a> <div><a href="/profile/hithu" title="Pupil hithu" class="rated-user user-green">hithu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:09">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807124" href="?#comment-807124" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="202138" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807124"> <div class="moveup"> <div class="ttypography"><p>Still don't understand editorial of D, can anybody explain the two pointer technique?</p></div> </div> </div> <div class="reply info"> <a class="comment-807124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807124"> <li> <div class="comment"> <table class="comment-table" commentId="807128" commentParentId="807124"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Enigma20" style="position: relative;"> <img src='https://userpic.codeforces.org/1301418/avatar/3ba73a2cb1eeb8ef.jpg'/> </a> <div><a href="/profile/Enigma20" title="Expert Enigma20" class="rated-user user-blue">Enigma20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807128" href="?#comment-807128" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807124" style="font-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="807128" 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="807128" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="1301418" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807128"> <div class="moveup"> <div class="ttypography"><p>First we sort the array according to increasing order of $$$b_i$$$. Now, we maintain 2 pointers one at the start of the array(say $$$i$$$) and other one at the end(say $$$j$$$). Also, let's maintain two variables $$$cur$$$(stores number of products already taken), $$$ans$$$(stores the required answer).</p><p>Now, we run a loop until $$$i\leq j$$$.</p><p>If $$$cur\geq b_i$$$, there is no point to leave this product, so we buy all $$$a_i$$$ products with 50% discount and update our $$$cur$$$ and $$$ans$$$.</p><p>If $$$cur\lt b_i$$$, then we start from second pointer i.e. $$$j$$$ and keep taking $$$min(b_i-cur,a_j)$$$ products for 2 rubles, if $$$cur\lt b_j$$$, otherwise for 1 ruble. We stop once we have $$$cur\geq b_i$$$. Update $$$cur,ans,a_j$$$ accordingly. If $$$a_j=0$$$, decrement $$$j$$$.</p><p><a href="https://codeforces.com/contest/1539/submission/120108298">My submission</a></p><p>In this submission, I ran a loop until $$$i\lt j$$$ and checked $$$i=j$$$ condition separately but that isn't necessary.</p></div> </div> </div> <div class="reply info"> <a class="comment-807128 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807128 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807128"> <li> <div class="comment"> <table class="comment-table" commentId="807155" commentParentId="807128"> <tr> <td class="left"> <div style="position: absolute; left: 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/crozzhtt" style="position: relative;"> <img src='https://userpic.codeforces.org/1592985/avatar/ea9a2bfb02b015fb.jpg'/> </a> <div><a href="/profile/crozzhtt" title="Newbie crozzhtt" class="rated-user user-gray">crozzhtt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807155" href="?#comment-807155" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807128" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807155" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1592985" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807155"> <div class="moveup"> <div class="ttypography"><p>but when cur &lt; bi I wonder if I can choose to continue buying (i-1)th product for 1 ruble or buying j-th product for 2 rubles. Will the 2nd option be more optimal than the 1st option?</p></div> </div> </div> <div class="reply info"> <a class="comment-807155 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807155 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807155"> <li> <div class="comment"> <table class="comment-table" commentId="807161" commentParentId="807155"> <tr> <td class="left"> <div style="position: absolute; left: 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/Enigma20" style="position: relative;"> <img src='https://userpic.codeforces.org/1301418/avatar/3ba73a2cb1eeb8ef.jpg'/> </a> <div><a href="/profile/Enigma20" title="Expert Enigma20" class="rated-user user-blue">Enigma20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807161" href="?#comment-807161" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807155" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807161" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1301418" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807161"> <div class="moveup"> <div class="ttypography"><p>Yes, second case will be optimal. Look at it this way, you have to buy as many products for 50% discount as possible. Now we know $$$i^{th}$$$ product has smaller $$$b_i$$$, so the condition for discount of this product will be fulfilled by taking lesser number of products for 2 rubles. Also it may happen that after taking $$$i^{th}$$$ product for 50% discount, products with higher $$$b_i$$$ can be taken for 50% discount without additional cost of 2 rubles. So, 2nd case will be optimal.</p></div> </div> </div> <div class="reply info"> <a class="comment-807161 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807161 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807161"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807130" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/avdp" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/avdp" title="Newbie avdp" class="rated-user user-gray">avdp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807130" href="?#comment-807130" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807130" class="CommentVoteFrame" data-commentRating="97" data-commentUserId="1840186" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+97</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807130"> <div class="moveup"> <div class="ttypography"><p><img alt=" " src="/predownloaded/0d/c4/0dc4ee86562ac0c8d31bcf482bed113f62f1fda1.jpg" style="max-width: 100.0%;max-height: 100.0%;" /></p><p><a class="rated-user user-red" href="/profile/galen_colin" title="Международный гроссмейстер galen_colin">galen_colin</a> <strong>too</strong></p></div> </div> </div> <div class="reply info"> <a class="comment-807130 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807130 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807130"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807132" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Atomsky" style="position: relative;"> <img src='https://userpic.codeforces.org/336914/avatar/2c5685b756a63503.jpg'/> </a> <div><a href="/profile/Atomsky" title="Newbie Atomsky" class="rated-user user-gray">Atomsky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807132" href="?#comment-807132" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807132" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="336914" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807132"> <div class="moveup"> <div class="ttypography"><p>I submitted <a href="/contest/1539/submission/120147862" title="Посылка 120147862 от Atomsky">120147862</a> for Problem-C. It gave a wrong result on test 62 in GNU C++17. When I submitted the same code in C++11, it was accepted (<a href="/contest/1539/submission/120149347" title="Посылка 120149347 от Atomsky">120149347</a>).</p><p>It would be helpful if anyone tells me what went wrong in my code.</p></div> </div> </div> <div class="reply info"> <a class="comment-807132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807132"> <li> <div class="comment"> <table class="comment-table" commentId="807136" commentParentId="807132"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/avdp" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/avdp" title="Newbie avdp" class="rated-user user-gray">avdp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 06:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807136" href="?#comment-807136" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807136" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1840186" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807136"> <div class="moveup"> <div class="ttypography"><p>Hey there, It is because of precision error differences in C++11 and C++17, So it is always advised to use <strong>long double</strong> instead of <strong>double</strong>. You will get AC in both versions with <strong>long double</strong>.</p></div> </div> </div> <div class="reply info"> <a class="comment-807136 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807136 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807136"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807165" commentParentId="807132"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/maskman_lucifer" style="position: relative;"> <img src='https://userpic.codeforces.org/1453975/avatar/e7e8769e223b3ab9.jpg'/> </a> <div><a href="/profile/maskman_lucifer" title="Pupil maskman_lucifer" class="rated-user user-green">maskman_lucifer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807165" href="?#comment-807165" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807165" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1453975" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807165"> <div class="moveup"> <div class="ttypography"><p>In these cases use this (val + d-1 )/ d instead of some ceil on double (Try to avoid doubles if you can do the same with int (precision issue)).<br /> In your case foo[i] = (jar[i] — jar[i-1] + x-1)/x will be good to go.</p></div> </div> </div> <div class="reply info"> <a class="comment-807165 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807165 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807165"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807144" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/UpMing" style="position: relative;"> <img src='https://userpic.codeforces.org/1424136/avatar/2e9bc60a07619853.jpg'/> </a> <div><a href="/profile/UpMing" title="Candidate Master UpMing" class="rated-user user-violet">UpMing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 06:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807144" href="?#comment-807144" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807144" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="1424136" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807144"> <div class="moveup"> <div class="ttypography"><p>The difficulty range is very large,</p><p>For example, D through E</p></div> </div> </div> <div class="reply info"> <a class="comment-807144 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807144 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807144"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807157" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hurt_FOR_heart" style="position: relative;"> <img src='https://userpic.codeforces.org/1445761/avatar/4bd86d3c8cfb747a.jpg'/> </a> <div><a href="/profile/hurt_FOR_heart" title="Candidate Master hurt_FOR_heart" class="rated-user user-violet">hurt_FOR_heart</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807157" href="?#comment-807157" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807157" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="1445761" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807157"> <div class="moveup"> <div class="ttypography"><p>In problem E, i thing that it's hard to come up with such dp state. Does anyone have a more natural idea for this problem ? </p></div> </div> </div> <div class="reply info"> <a class="comment-807157 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807157 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807157"> <li> <div class="comment"> <table class="comment-table" commentId="807183" commentParentId="807157"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/andr14142" style="position: relative;"> <img src='https://userpic.codeforces.org/620444/avatar/368d81a28bf4f89b.jpg'/> </a> <div><a href="/profile/andr14142" title="Pupil andr14142" class="rated-user user-green">andr14142</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 08:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807183" href="?#comment-807183" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807157" style="font-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="807183" revisionCount="7" revision="7"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">7</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="807183" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="620444" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807183"> <div class="moveup"> <div class="ttypography"><p>A more natural idea is to calculate limits for both hands from the end.<br /> Last move has no limits. The range for both hands of last move is from 0 to m inclusive.<br /> For the previous move check cases. Initially limits impossible m &lt; k &lt; 0.<br /> If you can take the card into left hand, then check, could you keep your right hand for the next move? If left card may be kept, limits for the right hand are the current limits for right hand. Otherwise right hand must be kept for the next move, so intersect current limits for right hand with limits for next move.<br /> The same for the right hand.<br /> Finally we check limits for initial situation, is pair (0,0) allowed.</p></div> </div> </div> <div class="reply info"> <a class="comment-807183 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807183 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807183"> <li> <div class="comment"> <table class="comment-table" commentId="807186" commentParentId="807183"> <tr> <td class="left"> <div style="position: absolute; left: 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/rag-hav" style="position: relative;"> <img src='https://userpic.codeforces.org/1809311/avatar/8456dc0c30997ac5.jpg'/> </a> <div><a href="/profile/rag-hav" title="Expert rag-hav" class="rated-user user-blue">rag-hav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807186" href="?#comment-807186" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807183" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807186" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1809311" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807186"> <div class="moveup"> <div class="ttypography"><p>Isn't that exponential complexity? (two choices in every move)</p></div> </div> </div> <div class="reply info"> <a class="comment-807186 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807186 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807186"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807171" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/deletha" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/deletha" title="Pupil deletha" class="rated-user user-green">deletha</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807171" href="?#comment-807171" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807171" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1806788" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807171"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1539/submission/120173484" title="Посылка 120173484 от deletha">120173484</a> I am getting runtime error on test 23 in problem C. Unable to understand if it is due to seg fault or overflows. Can someone pls explain</p></div> </div> </div> <div class="reply info"> <a class="comment-807171 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807171 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807171"> <li> <div class="comment"> <table class="comment-table" commentId="807178" commentParentId="807171"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HowSoOrz" style="position: relative;"> <img src='https://userpic.codeforces.org/1519509/avatar/24d272c5a2a620a1.jpg'/> </a> <div><a href="/profile/HowSoOrz" title="Specialist HowSoOrz" class="rated-user user-cyan">HowSoOrz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 08:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807178" href="?#comment-807178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807171" style="font-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="807178" 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="807178" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1519509" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807178"> <div class="moveup"> <div class="ttypography"><p>Just return when the valid array size is 0. You cant use binary search when the size of the valid vector is 0. Reason: v.begin()=points to first element, v.end() points to next element of last ele.</p><p><a href="/contest/1539/submission/120176292" title="Посылка 120176292 от HowSoOrz">120176292</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807178"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807185" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noobKunal" style="position: relative;"> <img src='https://userpic.codeforces.org/1183443/avatar/73aa8f3ddfbcab8a.jpg'/> </a> <div><a href="/profile/noobKunal" title="Expert noobKunal" class="rated-user user-blue">noobKunal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807185" href="?#comment-807185" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807185" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1183443" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807185"> <div class="moveup"> <div class="ttypography"><p>Can anyone check <a href="https://codeforces.com/contest/1539/submission/120132934">my submission</a> for D. Its giving TLE at tc 11 and it seems that its because of initial sorting itself (and not even entering while loop).</p></div> </div> </div> <div class="reply info"> <a class="comment-807185 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807185 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807185"> <li> <div class="comment"> <table class="comment-table" commentId="807194" commentParentId="807185"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/i_aM_SnEhaal" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/i_aM_SnEhaal" title="Pupil i_aM_SnEhaal" class="rated-user user-green">i_aM_SnEhaal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807194" href="?#comment-807194" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807185" style="font-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="807194" 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="807194" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1279863" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807194"> <div class="moveup"> <div class="ttypography"><p>I tried to submit your solution with just by changing the compare function in sort and it worked. <a href="https://codeforces.com/contest/1539/submission/120179243">Here is the submission have a look</a> just compare it with your solution to see the changes I made.The problem was in how you are defining the compare function in sort. What I have understood is &lt;= or &gt;= is slower than &lt; or &gt; which is causing the problem. For more details please go through <a href="https://codeforces.com/blog/entry/70237">this blog</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-807194 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807194 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807194"> <li> <div class="comment"> <table class="comment-table" commentId="807201" commentParentId="807194"> <tr> <td class="left"> <div style="position: absolute; left: 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/noobKunal" style="position: relative;"> <img src='https://userpic.codeforces.org/1183443/avatar/73aa8f3ddfbcab8a.jpg'/> </a> <div><a href="/profile/noobKunal" title="Expert noobKunal" class="rated-user user-blue">noobKunal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807201" href="?#comment-807201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807194" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807201" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1183443" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807201"> <div class="moveup"> <div class="ttypography"><p>Thanks it passed. Wish i've known this before</p></div> </div> </div> <div class="reply info"> <a class="comment-807201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807201"> <li> <div class="comment"> <table class="comment-table" commentId="807205" commentParentId="807201"> <tr> <td class="left"> <div style="position: absolute; left: 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/i_aM_SnEhaal" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/i_aM_SnEhaal" title="Pupil i_aM_SnEhaal" class="rated-user user-green">i_aM_SnEhaal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807205" href="?#comment-807205" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807205" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1279863" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807205"> <div class="moveup"> <div class="ttypography"><p>I also learnt it the hard way. After getting TLE on TC 11 twice during the contest and then submitting the same code in 8 different ways after the contest was able to figure it out. </p></div> </div> </div> <div class="reply info"> <a class="comment-807205 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807205 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807205"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="1035068" commentParentId="807194"> <tr> <td class="left"> <div style="position: absolute; left: 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/BDboy" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BDboy" title="Expert BDboy" class="rated-user user-blue">BDboy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/05/2023 21:16">4 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1035068" href="?#comment-1035068" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807194" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1035068" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2468471" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1035068"> <div class="moveup"> <div class="ttypography"><p>Thanks, I wont be learning this the hard way. :)</p></div> </div> </div> <div class="reply info"> <a class="comment-1035068 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1035068 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1035068"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807188" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vkgainz" style="position: relative;"> <img src='https://userpic.codeforces.org/679880/avatar/f966b85a769e4f5.jpg'/> </a> <div><a href="/profile/vkgainz" title="Grandmaster vkgainz" class="rated-user user-red">vkgainz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:12">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807188" href="?#comment-807188" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807188" class="CommentVoteFrame" data-commentRating="51" data-commentUserId="679880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+51</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807188"> <div class="moveup"> <div class="ttypography"><p>I found D to be a lot easier to think about using binary search (which solves in $$$O(n\log(10^{14}))$$$. Similar to the editorial, sort with respect to $$$b_i$$$. Now, let $$$x$$$ be the number of items with price $$$1$$$ and $$$y$$$ be the number of items with price $$$2$$$. Then, our answer is equal to $$$x + 2 \cdot y = y + \sum_{i = 1} ^ {n} a_i$$$, so it suffices to minimize $$$y$$$.</p><p>Let's binary search on this. Suppose we set $$$y = k$$$. How do we know if this is enough? First we make two simple observations:</p> <ul> <li><p>We buy all $$$k$$$ items at the very beginning.</p></li> <li><p>We buy all $$$k$$$ items from a suffix of the sorted array.</p></li> </ul><p>Why does this work? Well, if you are going to buy $$$k$$$ items of price $$$2$$$, you should do it earlier than later, because then we might have more $$$b_i$$$ opened up that gives us items of price $$$1$$$. Similarly, we should be buying our items from a suffix because that way we can maximize the number of items of price $$$1$$$ we get (and, subsequently, minimize the number of items of price $$$2$$$). </p><p>From here it's simple to solve with binary search. To test $$$y = k$$$, start a counter for the number of items bought and an index at $$$0$$$. While the counter is greater than $$$b_{\text{index}}$$$, add $$$a_{\text{index}}$$$ to the counter (since we're getting all of those for price $$$1$$$) and increment the counter. If $$$k$$$ is enough, then the counter should be $$$\geq$$$ the number of items we have in total.</p><p>This explanation may seem a bit complicated, but the ideas involved are simple to arrive at and the implementation is very clean: <a href="https://codeforces.com/contest/1539/submission/120179122">my submission here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-807188 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807188 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807188"> <li> <div class="comment"> <table class="comment-table" commentId="807238" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ace-in-the-hole" style="position: relative;"> <img src='https://userpic.codeforces.org/725810/avatar/31d6d37857b526e4.jpg'/> </a> <div><a href="/profile/ace-in-the-hole" title="Candidate Master ace-in-the-hole" class="rated-user user-violet">ace-in-the-hole</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 12:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807238" href="?#comment-807238" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807238" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="725810" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807238"> <div class="moveup"> <div class="ttypography"><p>This idea is nice, but it's still not too different from the solution, because we still have to make the observation: buying items with higher b_i is better. I can say, your idea is <strong>not fundamentally different</strong> from the solution's idea. Maybe because this is not a hard problem so we can't see the diversity of the solutions like some others.</p><p>But it sure is a great idea, the thoughts &quot;I should minimize the number of bought items with price 2&quot;, &quot;I can binary search the answer on this&quot;, ... and more, as you explained, are completely natural and can be thought of. Thank you for your contribution!</p></div> </div> </div> <div class="reply info"> <a class="comment-807238 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807238 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807238"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807334" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/faraz16iqbal" style="position: relative;"> <img src='https://userpic.codeforces.org/1534426/avatar/6269999f6a6fd0c7.jpg'/> </a> <div><a href="/profile/faraz16iqbal" title="Expert faraz16iqbal" class="rated-user user-blue">faraz16iqbal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 17:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807334" href="?#comment-807334" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807334" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1534426" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807334"> <div class="moveup"> <div class="ttypography"><p>Thank you, brilliant explanation</p></div> </div> </div> <div class="reply info"> <a class="comment-807334 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807334 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807334"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807893" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeerInForestovo" style="position: relative;"> <img src='https://userpic.codeforces.org/805889/avatar/8210f0230414d9cc.jpg'/> </a> <div><a href="/profile/DeerInForestovo" title="Master DeerInForestovo" class="rated-user user-orange">DeerInForestovo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 12:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807893" href="?#comment-807893" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807893" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="805889" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807893"> <div class="moveup"> <div class="ttypography"><p>Thanks. In your solution, we finally found a proper position where the things before it were 1 and later than it were 2. So, why not check every possible position and keep some useful information? See <a href="https://codeforces.com/contest/1539/submission/120329507">my submission</a>, which is theoretically O(N) if we use radix sort instead of qsort.</p><p>Sorry for my bad English : )</p></div> </div> </div> <div class="reply info"> <a class="comment-807893 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807893 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807893"> <li> <div class="comment"> <table class="comment-table" commentId="807895" commentParentId="807893"> <tr> <td class="left"> <div style="position: absolute; left: 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/DeerInForestovo" style="position: relative;"> <img src='https://userpic.codeforces.org/805889/avatar/8210f0230414d9cc.jpg'/> </a> <div><a href="/profile/DeerInForestovo" title="Master DeerInForestovo" class="rated-user user-orange">DeerInForestovo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 12:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807895" href="?#comment-807895" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807893" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807895" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="805889" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807895"> <div class="moveup"> <div class="ttypography"><p>In my submission, 'Hab' meant 'Had bought'</p></div> </div> </div> <div class="reply info"> <a class="comment-807895 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807895 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807895"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="868233" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yeetholmes619" style="position: relative;"> <img src='https://userpic.codeforces.org/1957631/avatar/1ad3067143e8096e.jpg'/> </a> <div><a href="/profile/yeetholmes619" title="Expert yeetholmes619" class="rated-user user-blue">yeetholmes619</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/17/2021 01:45">22 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-868233" href="?#comment-868233" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="868233" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1957631" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-868233"> <div class="moveup"> <div class="ttypography"><p>I'm sorry for replying to your comment that is 6 months old, but reading this cleared all my doubts and troubles with this problem, I struggled with finding the right train of thought to solve this problem and the way you explained it removed all of my confusion regarding this.</p><p>The two pointer technique althought gives AC, didn't make the underlying idea behind the solution, i.e x+2y will be our minimum cost which can be re-written as ∑ai + y obvious to me, which your approach clearly does. Thanks a lot! your comment not only helped me in this problem but will help me in future problems as well as it gave light to the right mindset while solving the problem :)</p></div> </div> </div> <div class="reply info"> <a class="comment-868233 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-868233 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-868233"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807217" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Delver0227" style="position: relative;"> <img src='https://userpic.codeforces.org/1594171/avatar/5f6e96d412ba3fde.jpg'/> </a> <div><a href="/profile/Delver0227" title="Specialist Delver0227" class="rated-user user-cyan">Delver0227</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 10:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807217" href="?#comment-807217" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807217" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1594171" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807217"> <div class="moveup"> <div class="ttypography"><p>I have a different way of implementing problem D that is more concise. Considering buying items backwards, we want to the last item we buy is the item with the highest discount requirement(which can be achieved). Which means all we need to do is suppose we have already bought all the items and the number of items is $$$num$$$. Sorting $$$b_i$$$ in non-decreasing order, skip the items that are impossible to get a discount on and take $$$num_i = \min(num-b_i,a_i)$$$ as the number of $$$item_i$$$ which we can buy with a discount. Remember to substract $$$num_i$$$ from $$$num$$$. After iterating $$$i$$$ through all the items, the sum of $$$num_i$$$ is the total number of item that we can get a discount on.</p><p>The code goes like this:<a href="https://paste.ubuntu.com/p/8mwW8n2yfQ/">https://paste.ubuntu.com/p/8mwW8n2yfQ/</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807217 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807217 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807217"> <li> <div class="comment"> <table class="comment-table" commentId="809490" commentParentId="807217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Whimpers" style="position: relative;"> <img src='https://userpic.codeforces.org/1507315/avatar/b11dc9bbdf35d8d9.jpg'/> </a> <div><a href="/profile/Whimpers" title="Expert Whimpers" class="rated-user user-blue">Whimpers</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 03:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809490" href="?#comment-809490" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809490" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1507315" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809490"> <div class="moveup"> <div class="ttypography"><p>why does this work? dont 1's also count towards the total items bought. from what i can see from your solution it is just comparing if the number of items left is greater than the b of the current last item, but if there is an item that has a lot more a than it has b, wouldnt it also be useful in increasing the total number bought and thus would have to be used in the total number of items bought?</p></div> </div> </div> <div class="reply info"> <a class="comment-809490 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809490 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809490"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807229" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Samrev" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Samrev" title="Expert Samrev" class="rated-user user-blue">Samrev</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 11:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807229" href="?#comment-807229" style="font-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="807229" 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="807229" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="1932888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807229"> <div class="moveup"> <div class="ttypography"><p>Test:</p> <pre><code>5 3 10 2 12 1 11 3 10 1 8 </code></pre><p>Submission: <a href="/contest/1539/submission/120129309" title="Посылка 120129309 от Kakashi_099">120129309</a></p><p>Output : 20 Correct Output: 19</p><p>This submission is getting accepted but however the above test case shows wrong output. Correct Output should be 19, instead of 20.</p><p><a class="rated-user user-red" href="/profile/talant" title="Гроссмейстер talant">talant</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807229 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807229 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807229"> <li> <div class="comment"> <table class="comment-table" commentId="807256" commentParentId="807229"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/talant" style="position: relative;"> <img src='https://userpic.codeforces.org/1215930/avatar/cc80e217f41ccfb0.jpg'/> </a> <div><a href="/profile/talant" title="Grandmaster talant" class="rated-user user-red">talant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807256" href="?#comment-807256" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807229" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807256" class="CommentVoteFrame" data-commentRating="58" data-commentUserId="1215930" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+58</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807256"> <div class="moveup"> <div class="ttypography"><p>Stop tagging me, this task isn't even mine</p></div> </div> </div> <div class="reply info"> <a class="comment-807256 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807256 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807256"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807232" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Anish_Bashyal" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Anish_Bashyal" title="Pupil Anish_Bashyal" class="rated-user user-green">Anish_Bashyal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 12:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807232" href="?#comment-807232" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807232" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1411502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807232"> <div class="moveup"> <div class="ttypography"><p><strong>Problem D</strong></p><p>Proof that buying more items of some product than needed doesn't make the answer better. Let's suppose we have already achieved an product (say product A) which we can buy at discount. Now consider we have to buy next product (say product B). </p><p><strong>N</strong> be the number of product B we have to buy, and <strong>d</strong> be the total purchases required before discount and <strong>c</strong> be the amount of items we have already purchased. Then, </p><p><strong>Case I (buy more of product A and then B)</strong></p><p>Total cost for buying product B = <strong>(d-c)*1 + (N*1)</strong> = <strong>d-c+N</strong></p><p><strong>Case II (only buying product B)</strong></p><p>Total cost for buying product B = <strong>2 * (d-c) + ( N-( d-c ) )</strong> = <strong>d-c+N</strong> </p><p>So both the cases cost the same. But this is a special scenario. If we had different percentage of discount, then the above cases wouldn't be equal. </p><p>If we say <strong>m</strong> as discount percentage and <strong>x</strong> as normal price then, </p><p><strong>Case I</strong></p><p><em>mx(d-c) + Nmx</em></p><p><strong>Case II</strong></p><p><em>x(d-c) + (N-d+c)mx</em></p><p>Equating both cases, we get <strong>m = 0.5 or 50%</strong>..</p><p>So only when the discount percentage is 50%, buying more of a discounted product or buying only the required quantity of each products doesn't matter. Hence also in this case, doesn't matter.</p><p>Sorry for writing just the obvious algebra but wanted to share anyway :)</p></div> </div> </div> <div class="reply info"> <a class="comment-807232 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807232 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807232"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807240" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hurt_FOR_heart" style="position: relative;"> <img src='https://userpic.codeforces.org/1445761/avatar/4bd86d3c8cfb747a.jpg'/> </a> <div><a href="/profile/hurt_FOR_heart" title="Candidate Master hurt_FOR_heart" class="rated-user user-violet">hurt_FOR_heart</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807240" href="?#comment-807240" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807240" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="1445761" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807240"> <div class="moveup"> <div class="ttypography"><p>in E</p> <ul> <li>Card in query i fits constraints on value written on card in left hand in queries with indexes [i,j).</li> </ul><p>i think it's [i,j] isn't it ? Because we have card in i for query j too </p></div> </div> </div> <div class="reply info"> <a class="comment-807240 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807240 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807240"> <li> <div class="comment"> <table class="comment-table" commentId="807271" commentParentId="807240"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TeaTime" style="position: relative;"> <img src='https://userpic.codeforces.org/1199093/avatar/f1cbbd424f7d3cf7.jpg'/> </a> <div><a href="/profile/TeaTime" title="Master TeaTime" class="rated-user user-orange">TeaTime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:25">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807271" href="?#comment-807271" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807240" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807271" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="1199093" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807271"> <div class="moveup"> <div class="ttypography"><p>It's [i, j) because card j was already taken in right hand.</p></div> </div> </div> <div class="reply info"> <a class="comment-807271 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807271 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807271"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807273" commentParentId="807240"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TeaTime" style="position: relative;"> <img src='https://userpic.codeforces.org/1199093/avatar/f1cbbd424f7d3cf7.jpg'/> </a> <div><a href="/profile/TeaTime" title="Master TeaTime" class="rated-user user-orange">TeaTime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807273" href="?#comment-807273" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807240" style="font-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="807273" 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="807273" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="1199093" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807273"> <div class="moveup"> <div class="ttypography"><p>Oh, you are correct, I mistook it with something else. Thanks for noticing!</p><p>Edit: editorial was fixed.</p></div> </div> </div> <div class="reply info"> <a class="comment-807273 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807273 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807273"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807241" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pucuk16" style="position: relative;"> <img src='https://userpic.codeforces.org/1458650/avatar/a688a695b97d78cb.jpg'/> </a> <div><a href="/profile/pucuk16" title="Newbie pucuk16" class="rated-user user-gray">pucuk16</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807241" href="?#comment-807241" style="font-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="807241" 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="807241" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1458650" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807241"> <div class="moveup"> <div class="ttypography"><p>hai.. where my code gone wrong..? please help me..<br /> for problem C <br /> thx <a href="https://codeforces.com/contest/1539/submission/120116110">code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807241"> <li> <div class="comment"> <table class="comment-table" commentId="807335" commentParentId="807241"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bwxnQAQ" style="position: relative;"> <img src='https://userpic.codeforces.org/1816180/avatar/1179db2c2821d194.jpg'/> </a> <div><a href="/profile/bwxnQAQ" title="Expert bwxnQAQ" class="rated-user user-blue">bwxnQAQ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 17:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807335" href="?#comment-807335" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807241" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807335" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="1816180" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807335"> <div class="moveup"> <div class="ttypography"><p>You should check line 37.You change d continuously without initializing.The d on the right side of each formula in line 37 should be the d in line 32 instead of the last calculated d.</p></div> </div> </div> <div class="reply info"> <a class="comment-807335 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807335 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807335"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807251" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spookywooky" style="position: relative;"> <img src='https://userpic.codeforces.org/872585/avatar/a8efaf71cbe05928.jpg'/><img title='Почетный бейдж за поддержку Codeforces на его 10-летие' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/spookywooky" title="Specialist spookywooky" class="rated-user user-cyan">spookywooky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807251" href="?#comment-807251" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807251" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="872585" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807251"> <div class="moveup"> <div class="ttypography"><p>Explanation to E sounds like it would be possible to explain it in an understandable way.</p></div> </div> </div> <div class="reply info"> <a class="comment-807251 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807251 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807251"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807258" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807258" href="?#comment-807258" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807258" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807258"> <div class="moveup"> <div class="ttypography"><p><strong>If there is an item which costs 1, then we will not make the answer worse by buying this item.</strong></p><p>Why is that? For example, consider a situation where we've already bought all items, except for one, and it costs 2, and to make it cost 1 we need to buy 2 more items. In that case it would be cheaper to buy one left item and spend 2 instead of buing two more random items at cost 1 and finally buing one last item, spending 3 in total.</p></div> </div> </div> <div class="reply info"> <a class="comment-807258 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807258 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807258"> <li> <div class="comment"> <table class="comment-table" commentId="807275" commentParentId="807258"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807275" href="?#comment-807275" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807258" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807275" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807275"> <div class="moveup"> <div class="ttypography"><p>In your example you are explicitly making the cost of that item by buying more products of other items. But the statement means that if by buying other items and within limits i.e. less that $$$a_i$$$, then you should buy the items of cost 1.</p></div> </div> </div> <div class="reply info"> <a class="comment-807275 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807275 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807275"> <li> <div class="comment"> <table class="comment-table" commentId="807277" commentParentId="807275"> <tr> <td class="left"> <div style="position: absolute; left: 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/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:54">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807277" href="?#comment-807277" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807277" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807277"> <div class="moveup"> <div class="ttypography"><p>Thanks, that explains it:)</p></div> </div> </div> <div class="reply info"> <a class="comment-807277 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807277 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807277"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807331" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/NoobCpp" style="position: relative;"> <img src='https://userpic.codeforces.org/1716219/avatar/14a123abec8289d0.jpg'/> </a> <div><a href="/profile/NoobCpp" title="Specialist NoobCpp" class="rated-user user-cyan">NoobCpp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 17:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807331" href="?#comment-807331" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807331" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1716219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807331"> <div class="moveup"> <div class="ttypography"><p>Although E and F was more difficult than the rest, the contest was great. First time reach to Expert!!</p><p>Sr about my bad Eng :p</p></div> </div> </div> <div class="reply info"> <a class="comment-807331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807331"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807364" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/livlyf_168" style="position: relative;"> <img src='https://userpic.codeforces.org/1919608/avatar/cf064edf00e3eea6.jpg'/> </a> <div><a href="/profile/livlyf_168" title="Pupil livlyf_168" class="rated-user user-green">livlyf_168</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807364" href="?#comment-807364" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807364" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1919608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807364"> <div class="moveup"> <div class="ttypography"><p>Hey, can anyone help me with problem C. Don't know why is it giving WA on test 10. Below is my submission — <a href="/contest/1539/submission/120223010" title="Посылка 120223010 от livlyf_168">120223010</a>. I have used the same approach, except that I have taken The number of elements required to fill the gap as floor((d-1)/x). </p></div> </div> </div> <div class="reply info"> <a class="comment-807364 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807364 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807364"> <li> <div class="comment"> <table class="comment-table" commentId="807370" commentParentId="807364"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/itish" style="position: relative;"> <img src='https://userpic.codeforces.org/1589684/avatar/d4fea913edfbab4b.jpg'/> </a> <div><a href="/profile/itish" title="Candidate Master itish" class="rated-user user-violet">itish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807370" href="?#comment-807370" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807364" style="font-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="807370" 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="807370" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1589684" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807370"> <div class="moveup"> <div class="ttypography"><p>Change vector(int)split to vector(llint) split and it gets accepted</p></div> </div> </div> <div class="reply info"> <a class="comment-807370 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807370 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807370"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807374" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hotas" style="position: relative;"> <img src='https://userpic.codeforces.org/1150129/avatar/590cdb757ae4763a.jpg'/> </a> <div><a href="/profile/Hotas" title="Newbie Hotas" class="rated-user user-gray">Hotas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807374" href="?#comment-807374" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807374" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1150129" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807374"> <div class="moveup"> <div class="ttypography"><p>Can anyone tell me where am I doing wrong? I am getting wrong answer on test case 10. Problem C. Submission : <a href="/contest/1539/submission/120227942" title="Посылка 120227942 от Hotas">120227942</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807374 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807374 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807374"> <li> <div class="comment"> <table class="comment-table" commentId="807397" commentParentId="807374"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 20:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807397" href="?#comment-807397" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807374" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807397" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807397"> <div class="moveup"> <div class="ttypography"><p>I think the problem is that you have int[] a instead of ll[] a. Each element can be up to 1e18.</p></div> </div> </div> <div class="reply info"> <a class="comment-807397 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807397 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807397"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807378" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/coderaman327" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/coderaman327" title="Expert coderaman327" class="rated-user user-blue">coderaman327</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807378" href="?#comment-807378" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807378" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="886853" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807378"> <div class="moveup"> <div class="ttypography"><p>Can someone please tell me what my mistake is in problem D? <a href="https://codeforces.com/contest/1539/submission/120100696">My submission</a> Thanks in advance!!</p></div> </div> </div> <div class="reply info"> <a class="comment-807378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807378"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807400" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abyboi" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/abyboi" title="Pupil abyboi" class="rated-user user-green">abyboi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 21:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807400" href="?#comment-807400" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807400" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1833158" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807400"> <div class="moveup"> <div class="ttypography"><p>Can someone help me with Problem D? My submission is</p><p><a href="https://codeforces.com/contest/1539/submission/120232784">https://codeforces.com/contest/1539/submission/120232784</a></p><p>Thanks in advance!</p></div> </div> </div> <div class="reply info"> <a class="comment-807400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807400"> <li> <div class="comment"> <table class="comment-table" commentId="807478" commentParentId="807400"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/andr14142" style="position: relative;"> <img src='https://userpic.codeforces.org/620444/avatar/368d81a28bf4f89b.jpg'/> </a> <div><a href="/profile/andr14142" title="Pupil andr14142" class="rated-user user-green">andr14142</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 09:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807478" href="?#comment-807478" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807400" style="font-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="807478" 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="807478" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="620444" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807478"> <div class="moveup"> <div class="ttypography"><p>Your solution has not correct comparison in the case of whole buying goods without discount:<br /> else if (total_bought + products[j].F &lt; products[i].S)<br /> Correct comparison is:<br /> else if (total_bought + products[j].F &lt;= products[i].S)</p></div> </div> </div> <div class="reply info"> <a class="comment-807478 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807478 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807478"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807520" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Madara_Uzumaki" style="position: relative;"> <img src='https://userpic.codeforces.org/1621901/avatar/28eb09a48344e5fb.jpg'/> </a> <div><a href="/profile/Madara_Uzumaki" title="Newbie Madara_Uzumaki" class="rated-user user-gray">Madara_Uzumaki</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 11:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807520" href="?#comment-807520" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807520" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1621901" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807520"> <div class="moveup"> <div class="ttypography"><p>In <strong>problem</strong> C i ran the code in <strong>PyPy3</strong> the code got <strong>TLE in test case 18</strong> but when I ran the same code in <strong>Python3</strong> the code got <strong>accepted</strong> Can anyone clarify why did that happen?</p></div> </div> </div> <div class="reply info"> <a class="comment-807520 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807520 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807520"> <li> <div class="comment"> <table class="comment-table" commentId="807527" commentParentId="807520"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/casul" style="position: relative;"> <img src='https://userpic.codeforces.org/1690955/avatar/21ae0e21fe431dd7.jpg'/> </a> <div><a href="/profile/casul" title="Specialist casul" class="rated-user user-cyan">casul</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 12:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807527" href="?#comment-807527" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807520" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807527" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1690955" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807527"> <div class="moveup"> <div class="ttypography"><p>You may wanna check out this blog:</p><p><a href="https://codeforces.com/blog/entry/82989">https://codeforces.com/blog/entry/82989</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807527 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807527 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807527"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807629" commentParentId="807520"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aberent" 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/aberent" title="Specialist aberent" class="rated-user user-cyan">aberent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 18:13">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807629" href="?#comment-807629" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807520" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807629" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1157884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807629"> <div class="moveup"> <div class="ttypography"><p>I too got some strange behaviour with PyPy3 with test 18. Every version I tried printed a result and then (after it should have finished), got TLE. I wonder whether there is a bug somewhere here. See <a href="https://codeforces.com/blog/entry/92011">my blog entry</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-807629 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807629 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807629"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807566" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zvsevolod" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/zvsevolod" title="Newbie zvsevolod" class="rated-user user-gray">zvsevolod</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 14:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807566" href="?#comment-807566" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807566" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1271216" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807566"> <div class="moveup"> <div class="ttypography"><p>In problem C Java solution with Long[] array gets accepted, but long[] array solution gets TLE. (16th line in both solutions) </p><p>ACC: <a href="https://codeforces.com/contest/1539/submission/120284760">https://codeforces.com/contest/1539/submission/120284760</a> <br /> TLE: <a href="https://codeforces.com/contest/1539/submission/120284797">https://codeforces.com/contest/1539/submission/120284797</a></p><p>Could someone explain me why reference type works faster than primitive in this example?</p></div> </div> </div> <div class="reply info"> <a class="comment-807566 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807566 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807566"> <li> <div class="comment"> <table class="comment-table" commentId="807620" commentParentId="807566"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aberent" 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/aberent" title="Specialist aberent" class="rated-user user-cyan">aberent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 18:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807620" href="?#comment-807620" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807566" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807620" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1157884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807620"> <div class="moveup"> <div class="ttypography"><p>Apparently Java uses different sorting algorithms for integers (including longs) and objects. The algorithm for integers is generally faster, but its worst case is worse. You might have simply been unlucky. See the implementation notes for the two versions of sort: <a href="https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(long%5B%5D">https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(long%5B%5D</a>) <a href="https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(java.lang.Object%5B%5D">https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(java.lang.Object%5B%5D</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-807620 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807620 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807620"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807726" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/quinoa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/quinoa" title="Expert quinoa" class="rated-user user-blue">quinoa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 23:40">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807726" href="?#comment-807726" style="font-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="807726" 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="807726" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="592293" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807726"> <div class="moveup"> <div class="ttypography"><p>I had a hard time understanding the tutorial for problem E. This is my attempt at making it easier to understand.</p><p><strong>Easier problem: jump game</strong></p><p>Consider <a href="https://leetcode.com/problems/jump-game/">this</a> easier problem: you have an array $$$x$$$ where $$$x[i]$$$ means what the farthest is that you can jump from position $$$i$$$. Is it possible to reach the last element in the array if you start from position 0?</p><p>We can solve it with a DP where $$$dp[i]$$$ = can we reach the end if we start from position i? The solution to the problem is then equal to $$$dp[0]$$$. The transitions are like this: $$$dp[i]$$$ = $$$dp[i + 1]$$$ $$$||$$$ $$$dp[i + 2]$$$ $$$||$$$ ... $$$||$$$ $$$dp[i + x[i]]$$$. There are $$$N$$$ states and the transitions are $$$O(N)$$$ so this runs in $$$O(N^2)$$$.</p><p>We can make every transition $$$O(1)$$$ with a greedy insight. Instead of checking $$$dp[i + 1]$$$, ..., $$$dp[i + x[i]]$$$ we only need to check $$$dp[j]$$$ where $$$j$$$ is the leftmost position from which we can reach the end. The reason this works is that the leftmost position from which we can reach the end has the best probability of being within our jumping range. We can keep track of this leftmost position as we compute each state in a bottom up fashion.</p> <pre><code>int leftmost_possible = N - 1; for (int i = N - 2; i &gt;= 0; --i) { if (leftmost_possible &lt;= i + x[i]) { dp[i] = true; leftmost_possible = i; } } </code></pre><p><strong>Back to problem E</strong></p><p>We can again solve this with an $$$O(N^2)$$$ DP where $$$dp(x, y)$$$ = can we finish if card with index $$$x$$$ is in the left hand, and card with index $$$y$$$ is in the right hand (and we have just answered query $$$max(x, y)$$$). </p><p>We can notice that we can reduce the number of states to $$$N$$$. Because if we are at $$$dp(x, y)$$$ (WLOG $$$x &gt; y$$$) then</p> <ul> <li>either we will keep replacing the card in the left hand until we reach the end</li> <li>or at some point we have to take something in the right hand and we transition to state $$$dp(k, k + 1)$$$</li> </ul><p>So if we are at state (x, y) then in the next step either we are done, or we will transition to $$$dp(k, k + 1)$$$. Therefore (since we start at state $$$dp(0, 1)$$$) we will only visit states of the type $$$dp(k, k + 1)$$$ (and $$$dp(k - 1, k)$$$), and there are only $$$O(N)$$$ of those.</p><p>The transition is now $$$O(N)$$$ because we have to consider every $$$k$$$ such that $$$dp(k, k + 1)$$$ works. But with the same greedy insight as in the jump game problem we can reduce that to $$$O(1)$$$. Again we can store &quot;the leftmost k that works&quot; as we compute the states and therefore we can find the transition in $$$O(1)$$$.</p><p>Now of course in this problem another hard part is to compute the &quot;maximum jump length&quot; at every position. In the jump game problem this was given in the input, whereas here we have to compute it. For sure you can do it in logarithmic time with a segment tree (I saw it in <a href="https://www.youtube.com/watch?v=seaskdKf2sI">Colin Galen's video</a>). But apparently you can also do it in $$$O(1)$$$ since the solution runs in O(N) according to the tutorial. I didn't think about optimizing that part yet.</p></div> </div> </div> <div class="reply info"> <a class="comment-807726 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807726 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807726"> <li> <div class="comment"> <table class="comment-table" commentId="852194" commentParentId="807726"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ahshafi" style="position: relative;"> <img src='https://userpic.codeforces.org/818506/avatar/d65d006cfdce087a.jpg'/> </a> <div><a href="/profile/ahshafi" title="Candidate Master ahshafi" class="rated-user user-violet">ahshafi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/19/2021 17:24">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-852194" href="?#comment-852194" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807726" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="852194" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="818506" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-852194"> <div class="moveup"> <div class="ttypography"><p>me too confused about how to compute maximum jump length in O(1) </p></div> </div> </div> <div class="reply info"> <a class="comment-852194 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-852194 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-852194"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808157" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sg55" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sg55" title="Newbie sg55" class="rated-user user-gray">sg55</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/24/2021 05:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808157" href="?#comment-808157" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808157" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1445980" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808157"> <div class="moveup"> <div class="ttypography"><p>I have used 2 the same method as used by most of the other coders but my code is giving tle. Can please someone look and tell me why it is? <a href="/contest/1539/submission/120407076" title="Посылка 120407076 от sg55">120407076</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808157 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808157 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808157"> <li> <div class="comment"> <table class="comment-table" commentId="808253" commentParentId="808157"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zvsevolod" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/zvsevolod" title="Newbie zvsevolod" class="rated-user user-gray">zvsevolod</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/24/2021 13:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808253" href="?#comment-808253" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808157" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808253" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1271216" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808253"> <div class="moveup"> <div class="ttypography"><p>Try to use Long[] array instead of long[]. Also you may read my comment above.</p></div> </div> </div> <div class="reply info"> <a class="comment-808253 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808253 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808253"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hritik27" style="position: relative;"> <img src='https://userpic.codeforces.org/1232410/avatar/af014e1c10ef2a19.jpg'/> </a> <div><a href="/profile/hritik27" title="Newbie hritik27" class="rated-user user-gray">hritik27</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/24/2021 19:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808320" href="?#comment-808320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808320" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1232410" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808320"> <div class="moveup"> <div class="ttypography"><p>Can someone please help me with problem A?? Can't understand the solution give.</p></div> </div> </div> <div class="reply info"> <a class="comment-808320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808320"> <li> <div class="comment"> <table class="comment-table" commentId="810306" commentParentId="808320"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/songzy12" style="position: relative;"> <img src='https://userpic.codeforces.org/249570/avatar/3c83a5ef255ff4d6.jpg'/> </a> <div><a href="/profile/songzy12" title="Pupil songzy12" class="rated-user user-green">songzy12</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/30/2021 17:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810306" href="?#comment-810306" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808320" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810306" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="249570" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810306"> <div class="moveup"> <div class="ttypography"><p>1. First consider the case where there are infinite participants. Then each participant would be disturbed by $$$t/x$$$ participants following him. </p><p>2. Then consider the case that $$$n$$$ is finite but large enough, then the first participant would be disturbed by $$$t/x$$$, the same for participant 2, ..., until $$$k$$$. </p><p>For the participants beyond k, the number of participants that would disturb them are decreased by 1 each time, i.e., $$$t/x - 1$$$, $$$t/x - 2$$$, until 0 for the last participant.</p><p>There are $$$t/x$$$ numbers from $$$t/x - 1$$$ until 0, thus we know $$$k = n - t/x$$$.</p><p>So the answer would be $$$(n-t/x) * (t/x) + (t/x-1)*(t/x)/2$$$.</p><p>3. The $$$min$$$ and $$$max$$$ in the answer is to solve the case where n is not large enough, i.e., when $$$n &lt; t/x$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-810306 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810306 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810306"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808360" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/augurar" style="position: relative;"> <img src='https://userpic.codeforces.org/391071/avatar/8a814e47f9aacb44.jpg'/> </a> <div><a href="/profile/augurar" title="Expert augurar" class="rated-user user-blue">augurar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 02:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808360" href="?#comment-808360" style="font-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="808360" 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="808360" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="391071" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808360"> <div class="moveup"> <div class="ttypography"><p>I'm glad I didn't participate in this one officially. Problem C was easy but I kept getting a TLE for stupid language-specific reasons:</p> <ul> <li><p>My <a href="https://codeforces.com/contest/1539/submission/120478273">Python solution</a> got TLE on test 18 with PyPy3, but the same code passed with Python 3.</p></li> <li><p>My <a href="https://codeforces.com/contest/1539/submission/120478521">Java solution</a> got TLE on test 61, but passed if I changed <code>long[]</code> to <code>Long[]</code>. (This is kind of my fault for not knowing Java uses a worst-case O(n^2) sort for primitive arrays.)</p></li> <li><p>My <a href="https://codeforces.com/contest/1539/submission/120480356">C++ solution</a> passed with no special optimization.</p></li> </ul><p>In my opinion that's an indication that the time limit is overly strict, especially for an ABC problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-808360 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808360 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808360"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="816645" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/comseung18_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/comseung18_" title="Expert comseung18_" class="rated-user user-blue">comseung18_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/15/2021 09:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-816645" href="?#comment-816645" style="font-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="816645" 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="816645" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275870" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-816645"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1539/submission/122552751" title="Посылка 122552751 от comseung18_">122552751</a> why my solution A is not correct ? ans1 is Editorial solution ans2 is my solution</p><p>I checked my ans2 in many times. but ans1 equals ans2..<br />~~~~~ import random k = int(input()) for _ in range(k): n = random.randint(1,2*1000000000) x = random.randint(1,2*1000000000) t = random.randint(1,2*1000000000) tmp = t//x ans1 = max(0,n-tmp)*tmp + min(n-1,tmp-1)*min(n,tmp)//2 ans2 = tmp*n — tmp*tmp + tmp*n — ((2*n-tmp+1)*tmp)//2 if ans1 != ans2: print(ans1,ans2) ~~~~~</p></div> </div> </div> <div class="reply info"> <a class="comment-816645 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-816645 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-816645"> <li> <div class="comment"> <table class="comment-table" commentId="816647" commentParentId="816645"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/comseung18_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/comseung18_" title="Expert comseung18_" class="rated-user user-blue">comseung18_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/15/2021 09:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-816647" href="?#comment-816647" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-816645" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="816647" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275870" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-816647"> <div class="moveup"> <div class="ttypography"><p>when , t/x &gt; n , ans2 is wrong sorry</p></div> </div> </div> <div class="reply info"> <a class="comment-816647 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-816647 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-816647"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="984743" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PrickyToTheMoon" style="position: relative;"> <img src='https://userpic.codeforces.org/1432360/avatar/422cb9d88c769b8d.jpg'/> </a> <div><a href="/profile/PrickyToTheMoon" title="Pupil PrickyToTheMoon" class="rated-user user-green">PrickyToTheMoon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/24/2022 21:10">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-984743" href="?#comment-984743" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="984743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1432360" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-984743"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1539/submission/186604051" title="Submission 186604051 by PrickyToTheMoon">186604051</a></p><p>Please help. Cannot understand why getting WA on test case 18. My approach matches perfectly with editorial.</p><p>Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-984743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-984743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-984743"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="995447" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mohsina_Shaikh" style="position: relative;"> <img src='https://userpic.codeforces.org/1396580/avatar/6f21616a2d8d578.jpg'/> </a> <div><a href="/profile/Mohsina_Shaikh" title="Newbie Mohsina_Shaikh" class="rated-user user-gray">Mohsina_Shaikh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/25/2023 07:37">8 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-995447" href="?#comment-995447" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="995447" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1396580" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-995447"> <div class="moveup"> <div class="ttypography"><p>can anyone please explain how problem B can be solved using DP.</p></div> </div> </div> <div class="reply info"> <a class="comment-995447 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-995447 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-995447"> </ul> </div> <br/> <div id="editBox-100475" 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 firstPreview100475 = true; var lastPreviewContent100475 = ''; 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=100475] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=100475] 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-92516").click(function () { $.post("/data/topic/vote", {topicId: 92516, _tta: Codeforces.tta(), topicRevisionId: 229854, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-92516").click(function () { $.post("/data/topic/vote", {topicId: 92516, _tta: Codeforces.tta(), topicRevisionId: 229854, 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:33:26</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:'81289365b9230c42',t:'MTY5NjcwNzIwNi44NDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1539E
1539
E
ru
E. Игра с картами
<div class="problem-statement"><div class="header"><div class="title">E. Игра с картами</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Алисы сломался компьютер и теперь она не может играть в свою любимую карточную игру. Чтобы помочь Алисе, Боб решил помочь ей и ответить на $$$n$$$ запросов. </p><p>Изначально в левой и правой руке Боб держит по одной карте с числом $$$0$$$, записанным на этих картах. Во время выполнения $$$i$$$-го запроса Алиса предлагает Бобу заменить карту в правой или левой руке на карту с числом $$$k_i$$$ (Боб выбирает, какую из карт заменить, Боб обязан заменить ровно одну карту).</p><p>После замены карты Алиса хочет, чтобы число на левой и правой картах принадлежали каким-то заданным отрезкам (отрезки для левой и правой карты могут быть различны). Формально, пусть число записанное на левой карте — $$$x$$$, а на правой — $$$y$$$. Тогда после замены карты на $$$i$$$-м запросе должно выполняться, что $$$a_{l, i} \le x \le b_{l, i}$$$ и $$$a_{r, i} \le y \le b_{r,i}$$$.</p><p>Скажите, сможет ли Боб ответить на все запросы, чтобы все условия удовлетворялись. Если ответить на все запросы возможно, то приведите способ это сделать.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке вводятся два целых числа $$$n$$$ и $$$m$$$ ($$$2 \le n \le 100\,000$$$, $$$2 \le m \le 10^9$$$) — количество запросов и максимально возможное значение на карте.</p><p>Далее следует описание $$$n$$$ запросов. Описание каждого запроса состоит из трех строк.</p><p>В первой строке описания $$$i$$$-го запроса вводится целое число $$$k_i$$$ ($$$0 \le k_i \le m$$$) — число, записанное на новой карте.</p><p>Во второй строке описания $$$i$$$-го запроса вводятся два целых числа $$$a_{l, i}$$$ и $$$b_{l, i}$$$ ($$$0 \le a_{l, i} \le b_{l, i} \le m$$$) — минимальное и максимальное допустимые значения, записанные на карте в левой руке после замены.</p><p>Во третьей строке описания $$$i$$$-го запроса вводятся два целых числа $$$a_{r, i}$$$ и $$$b_{r,i}$$$ ($$$0 \le a_{r, i} \le b_{r,i} \le m$$$) — минимальное и максимальное допустимые значения, записанные на карте в правой руке после замены.</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>Если Боб может ответить на все $$$n$$$ запросов, то во второй строке выходных данных должны содержаться $$$n$$$ чисел, соответствующих корректному способу ответить на все запросы. Если в ответ на $$$i$$$-й запрос Бобу нужно взять карту в левую руку, выведите $$$0$$$, иначе выведите $$$1$$$. Если существует несколько корректных способов ответить на запросы, то любой из них будет засчитан.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 10 3 0 3 0 2 2 0 4 0 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes 0 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 10 3 0 3 0 2 2 3 4 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No</pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 10 3 0 3 0 3 7 4 7 1 3 2 2 3 3 7 8 1 8 1 8 6 1 6 7 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes 1 0 0 1 0 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="f2ec8e627721a0bf013ebeb0d3815f9c"/> <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="3b3d6aa18ec7f2c8636f747ba32c1b3c7997564d"/> <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='f2ec8e627721a0bf013ebeb0d3815f9c'>&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%2F1539%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='f2ec8e627721a0bf013ebeb0d3815f9c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1539">Codeforces Round 727 (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='f2ec8e627721a0bf013ebeb0d3815f9c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1539/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *2500 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f2ec8e627721a0bf013ebeb0d3815f9c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1021674"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f2ec8e627721a0bf013ebeb0d3815f9c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1021674"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91905" title="Codeforces Round #727 (Div. 2, по Всероссийской олимпиаде имени Келдыша) [Рейтинговый]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13910:13911" 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/91906" title="tutorial" target="_blank">tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13923" 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/1539">Задачи</a></li> <li><a href="/contest/1539/submit">Отослать</a></li> <li><a href="/contest/1539/my">Мои посылки</a></li> <li><a href="/contest/1539/status">Статус</a></li> <li><a href="/contest/1539/hacks">Взломы</a></li> <li><a href="/contest/1539/room/1">Комната</a></li> <li><a href="/contest/1539/standings">Положение</a></li> <li><a href="/contest/1539/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_03cfc321a51bbe83623f48d310c5ffc6f1d29003"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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.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$$$ запросов. </p><p>Изначально в левой и правой руке Боб держит по одной карте с числом $$$0$$$, записанным на этих картах. Во время выполнения $$$i$$$-го запроса Алиса предлагает Бобу заменить карту в правой или левой руке на карту с числом $$$k_i$$$ (Боб выбирает, какую из карт заменить, Боб обязан заменить ровно одну карту).</p><p>После замены карты Алиса хочет, чтобы число на левой и правой картах принадлежали каким-то заданным отрезкам (отрезки для левой и правой карты могут быть различны). Формально, пусть число записанное на левой карте — $$$x$$$, а на правой — $$$y$$$. Тогда после замены карты на $$$i$$$-м запросе должно выполняться, что $$$a_{l, i} \le x \le b_{l, i}$$$ и $$$a_{r, i} \le y \le b_{r,i}$$$.</p><p>Скажите, сможет ли Боб ответить на все запросы, чтобы все условия удовлетворялись. Если ответить на все запросы возможно, то приведите способ это сделать.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке вводятся два целых числа $$$n$$$ и $$$m$$$ ($$$2 \le n \le 100\,000$$$, $$$2 \le m \le 10^9$$$) — количество запросов и максимально возможное значение на карте.</p><p>Далее следует описание $$$n$$$ запросов. Описание каждого запроса состоит из трех строк.</p><p>В первой строке описания $$$i$$$-го запроса вводится целое число $$$k_i$$$ ($$$0 \le k_i \le m$$$) — число, записанное на новой карте.</p><p>Во второй строке описания $$$i$$$-го запроса вводятся два целых числа $$$a_{l, i}$$$ и $$$b_{l, i}$$$ ($$$0 \le a_{l, i} \le b_{l, i} \le m$$$) — минимальное и максимальное допустимые значения, записанные на карте в левой руке после замены.</p><p>Во третьей строке описания $$$i$$$-го запроса вводятся два целых числа $$$a_{r, i}$$$ и $$$b_{r,i}$$$ ($$$0 \le a_{r, i} \le b_{r,i} \le m$$$) — минимальное и максимальное допустимые значения, записанные на карте в правой руке после замены.</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>Если Боб может ответить на все $$$n$$$ запросов, то во второй строке выходных данных должны содержаться $$$n$$$ чисел, соответствующих корректному способу ответить на все запросы. Если в ответ на $$$i$$$-й запрос Бобу нужно взять карту в левую руку, выведите $$$0$$$, иначе выведите $$$1$$$. Если существует несколько корректных способов ответить на запросы, то любой из них будет засчитан.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 10 3 0 3 0 2 2 0 4 0 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes 0 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 10 3 0 3 0 2 2 3 4 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No</pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 10 3 0 3 0 3 7 4 7 1 3 2 2 3 3 7 8 1 8 1 8 6 1 6 7 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes 1 0 0 1 0 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c6adba669daa',t:'MTY5NjY2NzM2My41NjQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2500"]
https://codeforces.com/blog/entry/91906
<!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="c4ae3f1dbdd3aa7685e27f571fc144d8"/> <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="Codeforces Round #727 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #727 Editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='c4ae3f1dbdd3aa7685e27f571fc144d8'>&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%2F91906">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='c4ae3f1dbdd3aa7685e27f571fc144d8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:31:34</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:31:34</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='c4ae3f1dbdd3aa7685e27f571fc144d8'/> <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="92516"> <div class="title"> <a href="/blog/entry/91906"> <p>Codeforces Round #727 Editorial</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="Jun/18/2021 00:11">2 years ago</span>, translation, <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/1539/problem/A" title="Codeforces Round 727 (Div. 2)">1539A - Contest Start</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/1539/problem/B" title="Codeforces Round 727 (Div. 2)">1539B - Love Song</a> was authored by jury and prepared by <a class="rated-user user-red" href="/profile/talant" title="Grandmaster talant">talant</a></p><p><a href="/contest/1539/problem/C" title="Codeforces Round 727 (Div. 2)">1539C - Stable Groups</a> was authored by <a class="rated-user user-orange" href="/profile/Artyom123" title="International Master Artyom123">Artyom123</a> and prepared by <a class="rated-user user-orange" href="/profile/Artyom123" title="International Master Artyom123">Artyom123</a> and <a class="rated-user user-blue" href="/profile/shishyando" title="Expert shishyando">shishyando</a></p><p><a href="/contest/1539/problem/D" title="Codeforces Round 727 (Div. 2)">1539D - PriceFixed</a> was authored by Helen Andreeva and prepared by <a class="rated-user user-red" href="/profile/Siberian" title="Grandmaster Siberian">Siberian</a></p><p><a href="/contest/1539/problem/E" title="Codeforces Round 727 (Div. 2)">1539E - Game with Cards</a> was authored and prepared by <a class="rated-user user-orange" href="/profile/TeaTime" title="Master TeaTime">TeaTime</a></p><p><a href="/contest/1539/problem/F" title="Codeforces Round 727 (Div. 2)">1539F - Strange Array</a> was authored and prepared by <a class="rated-user user-orange" href="/profile/Tikhon228" title="Master Tikhon228">Tikhon228</a></p> <div class="problemTutorial" problemcode="1539A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539C">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539D">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539E">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539F">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/1539" class="notice" style="text-decoration: none;">Codeforces Round 727 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-42191-92516").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: "91906", 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> <span style="padding: 0 0.35em;"> <a href="/search?query=%23727" class="tag notice" style="text-decoration: none;">#727</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-92516"><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'>+79</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-92516"><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="Jun/18/2021 00:11">2 years ago</span> </li> <li> <a href="/blog/entry/91906#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/91906#comments"> 116 </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="100475"> <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 (81)</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="807107" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hhoppitree" style="position: relative;"> <img src='https://userpic.codeforces.org/1366950/avatar/874468310bfb5ee5.jpg'/> </a> <div><a href="/profile/hhoppitree" title="Grandmaster hhoppitree" class="rated-user user-red">hhoppitree</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 01:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807107" href="?#comment-807107" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807107" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1366950" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807107"> <div class="moveup"> <div class="ttypography"><p>A great competition with hacking :)</p></div> </div> </div> <div class="reply info"> <a class="comment-807107 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807107 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807107"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807116" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iLoveIOI" style="position: relative;"> <img src='https://userpic.codeforces.org/483613/avatar/19b4d34a35f1e022.jpg'/> </a> <div><a href="/profile/iLoveIOI" title="Master iLoveIOI" class="rated-user user-orange">iLoveIOI</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 03:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807116" href="?#comment-807116" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807116" class="CommentVoteFrame" data-commentRating="34" data-commentUserId="483613" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+34</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807116"> <div class="moveup"> <div class="ttypography"><p>Can someone explain one of the multiset solutions to E? Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-807116 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807116 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807116"> <li> <div class="comment"> <table class="comment-table" commentId="807421" commentParentId="807116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lazywitt" style="position: relative;"> <img src='https://userpic.codeforces.org/995139/avatar/e4276e734c1b167e.jpg'/> </a> <div><a href="/profile/lazywitt" title="Pupil lazywitt" class="rated-user user-green">lazywitt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 21:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807421" href="?#comment-807421" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807116" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807421" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="995139" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807421"> <div class="moveup"> <div class="ttypography"><p>Can you show any multiset solutions which passed ? </p></div> </div> </div> <div class="reply info"> <a class="comment-807421 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807421 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807421"> <li> <div class="comment"> <table class="comment-table" commentId="807448" commentParentId="807421"> <tr> <td class="left"> <div style="position: absolute; left: 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/iLoveIOI" style="position: relative;"> <img src='https://userpic.codeforces.org/483613/avatar/19b4d34a35f1e022.jpg'/> </a> <div><a href="/profile/iLoveIOI" title="Master iLoveIOI" class="rated-user user-orange">iLoveIOI</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 04:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807448" href="?#comment-807448" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807421" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807448" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="483613" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807448"> <div class="moveup"> <div class="ttypography"><p>For example, <a href="https://codeforces.com/contest/1539/submission/120110352">this</a> and <a href="https://codeforces.com/contest/1539/submission/120092916">this</a>. </p></div> </div> </div> <div class="reply info"> <a class="comment-807448 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807448 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807448"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807484" commentParentId="807116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lucaperju" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lucaperju" title="International Grandmaster lucaperju" class="rated-user user-red">lucaperju</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 09:45">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807484" href="?#comment-807484" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807116" style="font-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="807484" 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="807484" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="627011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807484"> <div class="moveup"> <div class="ttypography"><p>Consider dpL[i][j] (different from the one from the editorial) as equal to 1 if it's possible to take the first i cards, ith one in the left hand, and j being the last card we took in the right hand (j&lt;i). And, dpR[j][i] as equal to 1 if it's possible to take the first i cards, last one in the right hand, and j being the last card we took in the left hand. then, instead of storing the whole array, let L[i] be a set (or multiset) of pairs of &lt;k[j],j&gt; such that dpL[i][j] is 1, (and the same for R[i]). Now, if we're at step i and know L[i] and R[i], let's try to compute L[i+1] and R[i+1]: Let's focus on computing L[i+1], for R[i+1] it's similar: if (i+1)th card can't go in the left hand, then L[i+1] will be empty, let's assume it can go there. Let's also assume that the (i+1)th right hand can take any card, we'll fix that later. Then, first of all, if the set R[i] is not empty, we should add the pair &lt;k[i],i&gt; to L[i+1], that's because we can go from having the cards from (j, i) to (i+1, i) by taking the i+1th card in the left hand. And, let's also add to L[i+1] all the pairs from L[i], because we can get those by going from (i, j) to (i+1, j). Now, I assumed that the (i+1)th right hand can take any card, while in reality it can only take those whose k is between ar[i+1] and br[i+1]. So, let's erase from L[i+1] the pairs that are not valid. Since it's a set, we can just erase the smallest card values and the highest card values from the set which are not in the interval. This might seem like it's too slow, but it's actually amortized, because at each step, we only add at most one new pair to the set ( the pair &lt;k[i], i&gt; ), and delete some of the pairs which aren't valid. I'm not sure if I explained this very well, I hope it's clear.</p></div> </div> </div> <div class="reply info"> <a class="comment-807484 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807484 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807484"> <li> <div class="comment"> <table class="comment-table" commentId="807490" commentParentId="807484"> <tr> <td class="left"> <div style="position: absolute; left: 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/iLoveIOI" style="position: relative;"> <img src='https://userpic.codeforces.org/483613/avatar/19b4d34a35f1e022.jpg'/> </a> <div><a href="/profile/iLoveIOI" title="Master iLoveIOI" class="rated-user user-orange">iLoveIOI</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 10:26">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807490" href="?#comment-807490" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807484" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807490" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="483613" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807490"> <div class="moveup"> <div class="ttypography"><p>Ah, I see thanks a lot! It was very clear :)</p></div> </div> </div> <div class="reply info"> <a class="comment-807490 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807490 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807490"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807916" commentParentId="807484"> <tr> <td class="left"> <div style="position: absolute; left: 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/Mrajaryan" style="position: relative;"> <img src='https://userpic.codeforces.org/1377953/avatar/e904b3a3a2eac1ad.jpg'/> </a> <div><a href="/profile/Mrajaryan" title="Newbie Mrajaryan" class="rated-user user-gray">Mrajaryan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 13:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807916" href="?#comment-807916" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807484" style="font-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="807916" 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="807916" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1377953" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807916"> <div class="moveup"> <div class="ttypography"><p>Thanks for explanation. But I can't understand why I should use dp? Can you please give some idea on this ? Or just tell me the naive approach by which i can solve the problem? Like naive dp approach</p></div> </div> </div> <div class="reply info"> <a class="comment-807916 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807916 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807916"> <li> <div class="comment"> <table class="comment-table" commentId="807995" commentParentId="807916"> <tr> <td class="left"> <div style="position: absolute; left: 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/lucaperju" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lucaperju" title="International Grandmaster lucaperju" class="rated-user user-red">lucaperju</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 17:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807995" href="?#comment-807995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807916" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807995" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="627011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807995"> <div class="moveup"> <div class="ttypography"><p>A naive dp approach using the same dp I described above would be: dpL[i][j] (j&lt;i) is true if, obviously, ith card can stay in the left hand (at step i), and jth card can stay in the right hand (at step i), and either:</p> <ul> <li><p>j &lt; (i-1), and dpL[i-1][j] is true</p></li> <li><p>OR j == (i-1), and there exists such k &lt; (i-1) so that dpR[k][i-1] is true</p></li> </ul><p>And similarly for dpR. After calculating this, you can easily recreate the solution from right to left.</p></div> </div> </div> <div class="reply info"> <a class="comment-807995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807995"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="810899" commentParentId="807484"> <tr> <td class="left"> <div style="position: absolute; left: 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/vishaaaal" style="position: relative;"> <img src='https://userpic.codeforces.org/1443354/avatar/25a2dd924894eeeb.jpg'/> </a> <div><a href="/profile/vishaaaal" title="Expert vishaaaal" class="rated-user user-blue">vishaaaal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/02/2021 20:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810899" href="?#comment-810899" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807484" style="font-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="810899" 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="810899" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1443354" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-810899"> <div class="moveup"> <div class="ttypography"><p>How will the following be represented according to these dp states?</p><p>We can pick all the cards upto the ith card in the left hand but none of them in the right hand (in other words, all the queries are answered on the left hand upto the ith card). </p><p>This would imply that there is no j such that dpL[i][j] is 1. But still we can answer all the queries upto the ith card.</p><p>Edit: I thought a lil bit about it and I think we can use 0 as a dummy card (which basically means, by default we'll have 0 as a card in right hand if we don't pick any card in it). And yess, AC. Great explanation OFZ.</p></div> </div> </div> <div class="reply info"> <a class="comment-810899 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810899 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810899"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807117" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Acfboy" style="position: relative;"> <img src='https://userpic.codeforces.org/873793/avatar/146c53315bccb6e9.jpg'/> </a> <div><a href="/profile/Acfboy" title="Master Acfboy" class="rated-user user-orange">Acfboy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 03:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807117" href="?#comment-807117" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807117" class="CommentVoteFrame" data-commentRating="61" data-commentUserId="873793" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+61</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807117"> <div class="moveup"> <div class="ttypography"><p>Nice problems, but the gap between problem ABCD and EF seems too large.</p></div> </div> </div> <div class="reply info"> <a class="comment-807117 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807117 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807117"> <li> <div class="comment"> <table class="comment-table" commentId="807121" commentParentId="807117"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807121" href="?#comment-807121" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807117" style="font-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="807121" 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="807121" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807121"> <div class="moveup"> <div class="ttypography"><p>I think there is a mistake in the editorial of the Problem F.</p><p>The editorial said if the $$$a_i$$$ is less than or equal to the median element then $$$ans = \left\lfloor\dfrac{cnt_R+cnt_M-cnt_L+1}{2} \right\rfloor$$$, but if I have an array that is $$$[1, 2, 3, 4, 4, 6]$$$, the ans of the number $$$4$$$ should be 1, and if you use the formula mentioned above, you may get a wrong answer 0.</p><p>Could anyone tell me the correct formula?</p></div> </div> </div> <div class="reply info"> <a class="comment-807121 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807121 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807121"> <li> <div class="comment"> <table class="comment-table" commentId="807156" commentParentId="807121"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807156" href="?#comment-807156" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807121" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807156" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807156"> <div class="moveup"> <div class="ttypography"><p>The formula is correct, but it's for when the element come to the left of median. When element comes to right of median, other formula should be used which should give you 1. That's why we should take maximum from left &amp; right.</p></div> </div> </div> <div class="reply info"> <a class="comment-807156 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807156 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807156"> <li> <div class="comment"> <table class="comment-table" commentId="807196" commentParentId="807156"> <tr> <td class="left"> <div style="position: absolute; left: 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/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807196" href="?#comment-807196" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807156" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807196" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807196"> <div class="moveup"> <div class="ttypography"><p>Thank you very much. You're right and I have solved this problem by using two distinct formulas. </p></div> </div> </div> <div class="reply info"> <a class="comment-807196 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807196 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807196"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807159" commentParentId="807121"> <tr> <td class="left"> <div style="position: absolute; left: 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/Ka1hatsu" style="position: relative;"> <img src='https://userpic.codeforces.org/761494/avatar/5d5b8ffd577a29a8.jpg'/> </a> <div><a href="/profile/Ka1hatsu" title="Pupil Ka1hatsu" class="rated-user user-green">Ka1hatsu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807159" href="?#comment-807159" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807121" style="font-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="807159" 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="807159" class="CommentVoteFrame" data-commentRating="-6" data-commentUserId="761494" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807159"> <div class="moveup"> <div class="ttypography"><p>sorry</p></div> </div> </div> <div class="reply info"> <a class="comment-807159 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807159 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807159"> <li> <div class="comment"> <table class="comment-table" commentId="807192" commentParentId="807159"> <tr> <td class="left"> <div style="position: absolute; left: 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/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807192" href="?#comment-807192" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807159" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807192" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807192"> <div class="moveup"> <div class="ttypography"><p>I'm sorry but the median number is 4 according to the Problem F.</p></div> </div> </div> <div class="reply info"> <a class="comment-807192 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807192 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807192"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807120" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/highighiq" style="position: relative;"> <img src='https://userpic.codeforces.org/1420719/avatar/97be0e366e499727.jpg'/> </a> <div><a href="/profile/highighiq" title="Master highighiq" class="rated-user user-orange">highighiq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807120" href="?#comment-807120" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807120" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="1420719" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807120"> <div class="moveup"> <div class="ttypography"><p>Good problems!(But E,F is too difficult!) And I get to expert!</p></div> </div> </div> <div class="reply info"> <a class="comment-807120 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807120 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807120"> <li> <div class="comment"> <table class="comment-table" commentId="807122" commentParentId="807120"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807122" href="?#comment-807122" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807120" style="font-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="807122" 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="807122" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807122"> <div class="moveup"> <div class="ttypography"><p>Congratulations!</p></div> </div> </div> <div class="reply info"> <a class="comment-807122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807122"> <li> <div class="comment"> <table class="comment-table" commentId="807125" commentParentId="807122"> <tr> <td class="left"> <div style="position: absolute; left: 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/highighiq" style="position: relative;"> <img src='https://userpic.codeforces.org/1420719/avatar/97be0e366e499727.jpg'/> </a> <div><a href="/profile/highighiq" title="Master highighiq" class="rated-user user-orange">highighiq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:12">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807125" href="?#comment-807125" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807122" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807125" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1420719" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807125"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-807125 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807125 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807125"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807124" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hithu" style="position: relative;"> <img src='https://userpic.codeforces.org/202138/avatar/c537257b9e17f402.jpg'/> </a> <div><a href="/profile/hithu" title="Pupil hithu" class="rated-user user-green">hithu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:09">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807124" href="?#comment-807124" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="202138" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807124"> <div class="moveup"> <div class="ttypography"><p>Still don't understand editorial of D, can anybody explain the two pointer technique?</p></div> </div> </div> <div class="reply info"> <a class="comment-807124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807124"> <li> <div class="comment"> <table class="comment-table" commentId="807128" commentParentId="807124"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Enigma20" style="position: relative;"> <img src='https://userpic.codeforces.org/1301418/avatar/3ba73a2cb1eeb8ef.jpg'/> </a> <div><a href="/profile/Enigma20" title="Expert Enigma20" class="rated-user user-blue">Enigma20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807128" href="?#comment-807128" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807124" style="font-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="807128" 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="807128" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="1301418" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807128"> <div class="moveup"> <div class="ttypography"><p>First we sort the array according to increasing order of $$$b_i$$$. Now, we maintain 2 pointers one at the start of the array(say $$$i$$$) and other one at the end(say $$$j$$$). Also, let's maintain two variables $$$cur$$$(stores number of products already taken), $$$ans$$$(stores the required answer).</p><p>Now, we run a loop until $$$i\leq j$$$.</p><p>If $$$cur\geq b_i$$$, there is no point to leave this product, so we buy all $$$a_i$$$ products with 50% discount and update our $$$cur$$$ and $$$ans$$$.</p><p>If $$$cur\lt b_i$$$, then we start from second pointer i.e. $$$j$$$ and keep taking $$$min(b_i-cur,a_j)$$$ products for 2 rubles, if $$$cur\lt b_j$$$, otherwise for 1 ruble. We stop once we have $$$cur\geq b_i$$$. Update $$$cur,ans,a_j$$$ accordingly. If $$$a_j=0$$$, decrement $$$j$$$.</p><p><a href="https://codeforces.com/contest/1539/submission/120108298">My submission</a></p><p>In this submission, I ran a loop until $$$i\lt j$$$ and checked $$$i=j$$$ condition separately but that isn't necessary.</p></div> </div> </div> <div class="reply info"> <a class="comment-807128 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807128 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807128"> <li> <div class="comment"> <table class="comment-table" commentId="807155" commentParentId="807128"> <tr> <td class="left"> <div style="position: absolute; left: 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/crozzhtt" style="position: relative;"> <img src='https://userpic.codeforces.org/1592985/avatar/ea9a2bfb02b015fb.jpg'/> </a> <div><a href="/profile/crozzhtt" title="Newbie crozzhtt" class="rated-user user-gray">crozzhtt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807155" href="?#comment-807155" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807128" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807155" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1592985" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807155"> <div class="moveup"> <div class="ttypography"><p>but when cur &lt; bi I wonder if I can choose to continue buying (i-1)th product for 1 ruble or buying j-th product for 2 rubles. Will the 2nd option be more optimal than the 1st option?</p></div> </div> </div> <div class="reply info"> <a class="comment-807155 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807155 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807155"> <li> <div class="comment"> <table class="comment-table" commentId="807161" commentParentId="807155"> <tr> <td class="left"> <div style="position: absolute; left: 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/Enigma20" style="position: relative;"> <img src='https://userpic.codeforces.org/1301418/avatar/3ba73a2cb1eeb8ef.jpg'/> </a> <div><a href="/profile/Enigma20" title="Expert Enigma20" class="rated-user user-blue">Enigma20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807161" href="?#comment-807161" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807155" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807161" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1301418" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807161"> <div class="moveup"> <div class="ttypography"><p>Yes, second case will be optimal. Look at it this way, you have to buy as many products for 50% discount as possible. Now we know $$$i^{th}$$$ product has smaller $$$b_i$$$, so the condition for discount of this product will be fulfilled by taking lesser number of products for 2 rubles. Also it may happen that after taking $$$i^{th}$$$ product for 50% discount, products with higher $$$b_i$$$ can be taken for 50% discount without additional cost of 2 rubles. So, 2nd case will be optimal.</p></div> </div> </div> <div class="reply info"> <a class="comment-807161 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807161 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807161"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807130" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/avdp" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/avdp" title="Newbie avdp" class="rated-user user-gray">avdp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807130" href="?#comment-807130" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807130" class="CommentVoteFrame" data-commentRating="97" data-commentUserId="1840186" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+97</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807130"> <div class="moveup"> <div class="ttypography"><p><img alt=" " src="/predownloaded/0d/c4/0dc4ee86562ac0c8d31bcf482bed113f62f1fda1.jpg" style="max-width: 100.0%;max-height: 100.0%;" /></p><p><a class="rated-user user-red" href="/profile/galen_colin" title="Международный гроссмейстер galen_colin">galen_colin</a> <strong>too</strong></p></div> </div> </div> <div class="reply info"> <a class="comment-807130 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807130 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807130"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807132" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Atomsky" style="position: relative;"> <img src='https://userpic.codeforces.org/336914/avatar/2c5685b756a63503.jpg'/> </a> <div><a href="/profile/Atomsky" title="Newbie Atomsky" class="rated-user user-gray">Atomsky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807132" href="?#comment-807132" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807132" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="336914" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807132"> <div class="moveup"> <div class="ttypography"><p>I submitted <a href="/contest/1539/submission/120147862" title="Посылка 120147862 от Atomsky">120147862</a> for Problem-C. It gave a wrong result on test 62 in GNU C++17. When I submitted the same code in C++11, it was accepted (<a href="/contest/1539/submission/120149347" title="Посылка 120149347 от Atomsky">120149347</a>).</p><p>It would be helpful if anyone tells me what went wrong in my code.</p></div> </div> </div> <div class="reply info"> <a class="comment-807132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807132"> <li> <div class="comment"> <table class="comment-table" commentId="807136" commentParentId="807132"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/avdp" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/avdp" title="Newbie avdp" class="rated-user user-gray">avdp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 06:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807136" href="?#comment-807136" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807136" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1840186" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807136"> <div class="moveup"> <div class="ttypography"><p>Hey there, It is because of precision error differences in C++11 and C++17, So it is always advised to use <strong>long double</strong> instead of <strong>double</strong>. You will get AC in both versions with <strong>long double</strong>.</p></div> </div> </div> <div class="reply info"> <a class="comment-807136 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807136 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807136"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807165" commentParentId="807132"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/maskman_lucifer" style="position: relative;"> <img src='https://userpic.codeforces.org/1453975/avatar/e7e8769e223b3ab9.jpg'/> </a> <div><a href="/profile/maskman_lucifer" title="Pupil maskman_lucifer" class="rated-user user-green">maskman_lucifer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807165" href="?#comment-807165" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807165" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1453975" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807165"> <div class="moveup"> <div class="ttypography"><p>In these cases use this (val + d-1 )/ d instead of some ceil on double (Try to avoid doubles if you can do the same with int (precision issue)).<br /> In your case foo[i] = (jar[i] — jar[i-1] + x-1)/x will be good to go.</p></div> </div> </div> <div class="reply info"> <a class="comment-807165 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807165 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807165"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807144" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/UpMing" style="position: relative;"> <img src='https://userpic.codeforces.org/1424136/avatar/2e9bc60a07619853.jpg'/> </a> <div><a href="/profile/UpMing" title="Candidate Master UpMing" class="rated-user user-violet">UpMing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 06:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807144" href="?#comment-807144" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807144" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="1424136" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807144"> <div class="moveup"> <div class="ttypography"><p>The difficulty range is very large,</p><p>For example, D through E</p></div> </div> </div> <div class="reply info"> <a class="comment-807144 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807144 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807144"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807157" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hurt_FOR_heart" style="position: relative;"> <img src='https://userpic.codeforces.org/1445761/avatar/4bd86d3c8cfb747a.jpg'/> </a> <div><a href="/profile/hurt_FOR_heart" title="Candidate Master hurt_FOR_heart" class="rated-user user-violet">hurt_FOR_heart</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807157" href="?#comment-807157" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807157" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="1445761" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807157"> <div class="moveup"> <div class="ttypography"><p>In problem E, i thing that it's hard to come up with such dp state. Does anyone have a more natural idea for this problem ? </p></div> </div> </div> <div class="reply info"> <a class="comment-807157 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807157 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807157"> <li> <div class="comment"> <table class="comment-table" commentId="807183" commentParentId="807157"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/andr14142" style="position: relative;"> <img src='https://userpic.codeforces.org/620444/avatar/368d81a28bf4f89b.jpg'/> </a> <div><a href="/profile/andr14142" title="Pupil andr14142" class="rated-user user-green">andr14142</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 08:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807183" href="?#comment-807183" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807157" style="font-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="807183" revisionCount="7" revision="7"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">7</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="807183" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="620444" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807183"> <div class="moveup"> <div class="ttypography"><p>A more natural idea is to calculate limits for both hands from the end.<br /> Last move has no limits. The range for both hands of last move is from 0 to m inclusive.<br /> For the previous move check cases. Initially limits impossible m &lt; k &lt; 0.<br /> If you can take the card into left hand, then check, could you keep your right hand for the next move? If left card may be kept, limits for the right hand are the current limits for right hand. Otherwise right hand must be kept for the next move, so intersect current limits for right hand with limits for next move.<br /> The same for the right hand.<br /> Finally we check limits for initial situation, is pair (0,0) allowed.</p></div> </div> </div> <div class="reply info"> <a class="comment-807183 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807183 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807183"> <li> <div class="comment"> <table class="comment-table" commentId="807186" commentParentId="807183"> <tr> <td class="left"> <div style="position: absolute; left: 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/rag-hav" style="position: relative;"> <img src='https://userpic.codeforces.org/1809311/avatar/8456dc0c30997ac5.jpg'/> </a> <div><a href="/profile/rag-hav" title="Expert rag-hav" class="rated-user user-blue">rag-hav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807186" href="?#comment-807186" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807183" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807186" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1809311" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807186"> <div class="moveup"> <div class="ttypography"><p>Isn't that exponential complexity? (two choices in every move)</p></div> </div> </div> <div class="reply info"> <a class="comment-807186 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807186 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807186"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807171" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/deletha" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/deletha" title="Pupil deletha" class="rated-user user-green">deletha</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807171" href="?#comment-807171" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807171" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1806788" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807171"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1539/submission/120173484" title="Посылка 120173484 от deletha">120173484</a> I am getting runtime error on test 23 in problem C. Unable to understand if it is due to seg fault or overflows. Can someone pls explain</p></div> </div> </div> <div class="reply info"> <a class="comment-807171 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807171 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807171"> <li> <div class="comment"> <table class="comment-table" commentId="807178" commentParentId="807171"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HowSoOrz" style="position: relative;"> <img src='https://userpic.codeforces.org/1519509/avatar/24d272c5a2a620a1.jpg'/> </a> <div><a href="/profile/HowSoOrz" title="Specialist HowSoOrz" class="rated-user user-cyan">HowSoOrz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 08:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807178" href="?#comment-807178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807171" style="font-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="807178" 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="807178" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1519509" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807178"> <div class="moveup"> <div class="ttypography"><p>Just return when the valid array size is 0. You cant use binary search when the size of the valid vector is 0. Reason: v.begin()=points to first element, v.end() points to next element of last ele.</p><p><a href="/contest/1539/submission/120176292" title="Посылка 120176292 от HowSoOrz">120176292</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807178"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807185" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noobKunal" style="position: relative;"> <img src='https://userpic.codeforces.org/1183443/avatar/73aa8f3ddfbcab8a.jpg'/> </a> <div><a href="/profile/noobKunal" title="Expert noobKunal" class="rated-user user-blue">noobKunal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807185" href="?#comment-807185" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807185" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1183443" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807185"> <div class="moveup"> <div class="ttypography"><p>Can anyone check <a href="https://codeforces.com/contest/1539/submission/120132934">my submission</a> for D. Its giving TLE at tc 11 and it seems that its because of initial sorting itself (and not even entering while loop).</p></div> </div> </div> <div class="reply info"> <a class="comment-807185 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807185 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807185"> <li> <div class="comment"> <table class="comment-table" commentId="807194" commentParentId="807185"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/i_aM_SnEhaal" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/i_aM_SnEhaal" title="Pupil i_aM_SnEhaal" class="rated-user user-green">i_aM_SnEhaal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807194" href="?#comment-807194" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807185" style="font-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="807194" 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="807194" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1279863" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807194"> <div class="moveup"> <div class="ttypography"><p>I tried to submit your solution with just by changing the compare function in sort and it worked. <a href="https://codeforces.com/contest/1539/submission/120179243">Here is the submission have a look</a> just compare it with your solution to see the changes I made.The problem was in how you are defining the compare function in sort. What I have understood is &lt;= or &gt;= is slower than &lt; or &gt; which is causing the problem. For more details please go through <a href="https://codeforces.com/blog/entry/70237">this blog</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-807194 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807194 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807194"> <li> <div class="comment"> <table class="comment-table" commentId="807201" commentParentId="807194"> <tr> <td class="left"> <div style="position: absolute; left: 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/noobKunal" style="position: relative;"> <img src='https://userpic.codeforces.org/1183443/avatar/73aa8f3ddfbcab8a.jpg'/> </a> <div><a href="/profile/noobKunal" title="Expert noobKunal" class="rated-user user-blue">noobKunal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807201" href="?#comment-807201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807194" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807201" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1183443" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807201"> <div class="moveup"> <div class="ttypography"><p>Thanks it passed. Wish i've known this before</p></div> </div> </div> <div class="reply info"> <a class="comment-807201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807201"> <li> <div class="comment"> <table class="comment-table" commentId="807205" commentParentId="807201"> <tr> <td class="left"> <div style="position: absolute; left: 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/i_aM_SnEhaal" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/i_aM_SnEhaal" title="Pupil i_aM_SnEhaal" class="rated-user user-green">i_aM_SnEhaal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807205" href="?#comment-807205" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807205" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1279863" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807205"> <div class="moveup"> <div class="ttypography"><p>I also learnt it the hard way. After getting TLE on TC 11 twice during the contest and then submitting the same code in 8 different ways after the contest was able to figure it out. </p></div> </div> </div> <div class="reply info"> <a class="comment-807205 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807205 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807205"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="1035068" commentParentId="807194"> <tr> <td class="left"> <div style="position: absolute; left: 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/BDboy" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BDboy" title="Expert BDboy" class="rated-user user-blue">BDboy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/05/2023 21:16">4 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1035068" href="?#comment-1035068" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807194" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1035068" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2468471" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1035068"> <div class="moveup"> <div class="ttypography"><p>Thanks, I wont be learning this the hard way. :)</p></div> </div> </div> <div class="reply info"> <a class="comment-1035068 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1035068 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1035068"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807188" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vkgainz" style="position: relative;"> <img src='https://userpic.codeforces.org/679880/avatar/f966b85a769e4f5.jpg'/> </a> <div><a href="/profile/vkgainz" title="Grandmaster vkgainz" class="rated-user user-red">vkgainz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:12">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807188" href="?#comment-807188" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807188" class="CommentVoteFrame" data-commentRating="51" data-commentUserId="679880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+51</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807188"> <div class="moveup"> <div class="ttypography"><p>I found D to be a lot easier to think about using binary search (which solves in $$$O(n\log(10^{14}))$$$. Similar to the editorial, sort with respect to $$$b_i$$$. Now, let $$$x$$$ be the number of items with price $$$1$$$ and $$$y$$$ be the number of items with price $$$2$$$. Then, our answer is equal to $$$x + 2 \cdot y = y + \sum_{i = 1} ^ {n} a_i$$$, so it suffices to minimize $$$y$$$.</p><p>Let's binary search on this. Suppose we set $$$y = k$$$. How do we know if this is enough? First we make two simple observations:</p> <ul> <li><p>We buy all $$$k$$$ items at the very beginning.</p></li> <li><p>We buy all $$$k$$$ items from a suffix of the sorted array.</p></li> </ul><p>Why does this work? Well, if you are going to buy $$$k$$$ items of price $$$2$$$, you should do it earlier than later, because then we might have more $$$b_i$$$ opened up that gives us items of price $$$1$$$. Similarly, we should be buying our items from a suffix because that way we can maximize the number of items of price $$$1$$$ we get (and, subsequently, minimize the number of items of price $$$2$$$). </p><p>From here it's simple to solve with binary search. To test $$$y = k$$$, start a counter for the number of items bought and an index at $$$0$$$. While the counter is greater than $$$b_{\text{index}}$$$, add $$$a_{\text{index}}$$$ to the counter (since we're getting all of those for price $$$1$$$) and increment the counter. If $$$k$$$ is enough, then the counter should be $$$\geq$$$ the number of items we have in total.</p><p>This explanation may seem a bit complicated, but the ideas involved are simple to arrive at and the implementation is very clean: <a href="https://codeforces.com/contest/1539/submission/120179122">my submission here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-807188 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807188 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807188"> <li> <div class="comment"> <table class="comment-table" commentId="807238" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ace-in-the-hole" style="position: relative;"> <img src='https://userpic.codeforces.org/725810/avatar/31d6d37857b526e4.jpg'/> </a> <div><a href="/profile/ace-in-the-hole" title="Candidate Master ace-in-the-hole" class="rated-user user-violet">ace-in-the-hole</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 12:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807238" href="?#comment-807238" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807238" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="725810" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807238"> <div class="moveup"> <div class="ttypography"><p>This idea is nice, but it's still not too different from the solution, because we still have to make the observation: buying items with higher b_i is better. I can say, your idea is <strong>not fundamentally different</strong> from the solution's idea. Maybe because this is not a hard problem so we can't see the diversity of the solutions like some others.</p><p>But it sure is a great idea, the thoughts &quot;I should minimize the number of bought items with price 2&quot;, &quot;I can binary search the answer on this&quot;, ... and more, as you explained, are completely natural and can be thought of. Thank you for your contribution!</p></div> </div> </div> <div class="reply info"> <a class="comment-807238 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807238 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807238"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807334" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/faraz16iqbal" style="position: relative;"> <img src='https://userpic.codeforces.org/1534426/avatar/6269999f6a6fd0c7.jpg'/> </a> <div><a href="/profile/faraz16iqbal" title="Expert faraz16iqbal" class="rated-user user-blue">faraz16iqbal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 17:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807334" href="?#comment-807334" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807334" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1534426" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807334"> <div class="moveup"> <div class="ttypography"><p>Thank you, brilliant explanation</p></div> </div> </div> <div class="reply info"> <a class="comment-807334 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807334 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807334"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807893" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeerInForestovo" style="position: relative;"> <img src='https://userpic.codeforces.org/805889/avatar/8210f0230414d9cc.jpg'/> </a> <div><a href="/profile/DeerInForestovo" title="Master DeerInForestovo" class="rated-user user-orange">DeerInForestovo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 12:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807893" href="?#comment-807893" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807893" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="805889" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807893"> <div class="moveup"> <div class="ttypography"><p>Thanks. In your solution, we finally found a proper position where the things before it were 1 and later than it were 2. So, why not check every possible position and keep some useful information? See <a href="https://codeforces.com/contest/1539/submission/120329507">my submission</a>, which is theoretically O(N) if we use radix sort instead of qsort.</p><p>Sorry for my bad English : )</p></div> </div> </div> <div class="reply info"> <a class="comment-807893 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807893 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807893"> <li> <div class="comment"> <table class="comment-table" commentId="807895" commentParentId="807893"> <tr> <td class="left"> <div style="position: absolute; left: 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/DeerInForestovo" style="position: relative;"> <img src='https://userpic.codeforces.org/805889/avatar/8210f0230414d9cc.jpg'/> </a> <div><a href="/profile/DeerInForestovo" title="Master DeerInForestovo" class="rated-user user-orange">DeerInForestovo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 12:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807895" href="?#comment-807895" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807893" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807895" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="805889" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807895"> <div class="moveup"> <div class="ttypography"><p>In my submission, 'Hab' meant 'Had bought'</p></div> </div> </div> <div class="reply info"> <a class="comment-807895 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807895 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807895"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="868233" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yeetholmes619" style="position: relative;"> <img src='https://userpic.codeforces.org/1957631/avatar/1ad3067143e8096e.jpg'/> </a> <div><a href="/profile/yeetholmes619" title="Expert yeetholmes619" class="rated-user user-blue">yeetholmes619</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/17/2021 01:45">22 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-868233" href="?#comment-868233" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="868233" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1957631" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-868233"> <div class="moveup"> <div class="ttypography"><p>I'm sorry for replying to your comment that is 6 months old, but reading this cleared all my doubts and troubles with this problem, I struggled with finding the right train of thought to solve this problem and the way you explained it removed all of my confusion regarding this.</p><p>The two pointer technique althought gives AC, didn't make the underlying idea behind the solution, i.e x+2y will be our minimum cost which can be re-written as ∑ai + y obvious to me, which your approach clearly does. Thanks a lot! your comment not only helped me in this problem but will help me in future problems as well as it gave light to the right mindset while solving the problem :)</p></div> </div> </div> <div class="reply info"> <a class="comment-868233 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-868233 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-868233"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807217" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Delver0227" style="position: relative;"> <img src='https://userpic.codeforces.org/1594171/avatar/5f6e96d412ba3fde.jpg'/> </a> <div><a href="/profile/Delver0227" title="Specialist Delver0227" class="rated-user user-cyan">Delver0227</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 10:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807217" href="?#comment-807217" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807217" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1594171" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807217"> <div class="moveup"> <div class="ttypography"><p>I have a different way of implementing problem D that is more concise. Considering buying items backwards, we want to the last item we buy is the item with the highest discount requirement(which can be achieved). Which means all we need to do is suppose we have already bought all the items and the number of items is $$$num$$$. Sorting $$$b_i$$$ in non-decreasing order, skip the items that are impossible to get a discount on and take $$$num_i = \min(num-b_i,a_i)$$$ as the number of $$$item_i$$$ which we can buy with a discount. Remember to substract $$$num_i$$$ from $$$num$$$. After iterating $$$i$$$ through all the items, the sum of $$$num_i$$$ is the total number of item that we can get a discount on.</p><p>The code goes like this:<a href="https://paste.ubuntu.com/p/8mwW8n2yfQ/">https://paste.ubuntu.com/p/8mwW8n2yfQ/</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807217 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807217 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807217"> <li> <div class="comment"> <table class="comment-table" commentId="809490" commentParentId="807217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Whimpers" style="position: relative;"> <img src='https://userpic.codeforces.org/1507315/avatar/b11dc9bbdf35d8d9.jpg'/> </a> <div><a href="/profile/Whimpers" title="Expert Whimpers" class="rated-user user-blue">Whimpers</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 03:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809490" href="?#comment-809490" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809490" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1507315" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809490"> <div class="moveup"> <div class="ttypography"><p>why does this work? dont 1's also count towards the total items bought. from what i can see from your solution it is just comparing if the number of items left is greater than the b of the current last item, but if there is an item that has a lot more a than it has b, wouldnt it also be useful in increasing the total number bought and thus would have to be used in the total number of items bought?</p></div> </div> </div> <div class="reply info"> <a class="comment-809490 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809490 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809490"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807229" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Samrev" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Samrev" title="Expert Samrev" class="rated-user user-blue">Samrev</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 11:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807229" href="?#comment-807229" style="font-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="807229" 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="807229" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="1932888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807229"> <div class="moveup"> <div class="ttypography"><p>Test:</p> <pre><code>5 3 10 2 12 1 11 3 10 1 8 </code></pre><p>Submission: <a href="/contest/1539/submission/120129309" title="Посылка 120129309 от Kakashi_099">120129309</a></p><p>Output : 20 Correct Output: 19</p><p>This submission is getting accepted but however the above test case shows wrong output. Correct Output should be 19, instead of 20.</p><p><a class="rated-user user-red" href="/profile/talant" title="Гроссмейстер talant">talant</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807229 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807229 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807229"> <li> <div class="comment"> <table class="comment-table" commentId="807256" commentParentId="807229"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/talant" style="position: relative;"> <img src='https://userpic.codeforces.org/1215930/avatar/cc80e217f41ccfb0.jpg'/> </a> <div><a href="/profile/talant" title="Grandmaster talant" class="rated-user user-red">talant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807256" href="?#comment-807256" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807229" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807256" class="CommentVoteFrame" data-commentRating="58" data-commentUserId="1215930" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+58</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807256"> <div class="moveup"> <div class="ttypography"><p>Stop tagging me, this task isn't even mine</p></div> </div> </div> <div class="reply info"> <a class="comment-807256 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807256 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807256"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807232" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Anish_Bashyal" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Anish_Bashyal" title="Pupil Anish_Bashyal" class="rated-user user-green">Anish_Bashyal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 12:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807232" href="?#comment-807232" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807232" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1411502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807232"> <div class="moveup"> <div class="ttypography"><p><strong>Problem D</strong></p><p>Proof that buying more items of some product than needed doesn't make the answer better. Let's suppose we have already achieved an product (say product A) which we can buy at discount. Now consider we have to buy next product (say product B). </p><p><strong>N</strong> be the number of product B we have to buy, and <strong>d</strong> be the total purchases required before discount and <strong>c</strong> be the amount of items we have already purchased. Then, </p><p><strong>Case I (buy more of product A and then B)</strong></p><p>Total cost for buying product B = <strong>(d-c)*1 + (N*1)</strong> = <strong>d-c+N</strong></p><p><strong>Case II (only buying product B)</strong></p><p>Total cost for buying product B = <strong>2 * (d-c) + ( N-( d-c ) )</strong> = <strong>d-c+N</strong> </p><p>So both the cases cost the same. But this is a special scenario. If we had different percentage of discount, then the above cases wouldn't be equal. </p><p>If we say <strong>m</strong> as discount percentage and <strong>x</strong> as normal price then, </p><p><strong>Case I</strong></p><p><em>mx(d-c) + Nmx</em></p><p><strong>Case II</strong></p><p><em>x(d-c) + (N-d+c)mx</em></p><p>Equating both cases, we get <strong>m = 0.5 or 50%</strong>..</p><p>So only when the discount percentage is 50%, buying more of a discounted product or buying only the required quantity of each products doesn't matter. Hence also in this case, doesn't matter.</p><p>Sorry for writing just the obvious algebra but wanted to share anyway :)</p></div> </div> </div> <div class="reply info"> <a class="comment-807232 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807232 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807232"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807240" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hurt_FOR_heart" style="position: relative;"> <img src='https://userpic.codeforces.org/1445761/avatar/4bd86d3c8cfb747a.jpg'/> </a> <div><a href="/profile/hurt_FOR_heart" title="Candidate Master hurt_FOR_heart" class="rated-user user-violet">hurt_FOR_heart</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807240" href="?#comment-807240" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807240" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="1445761" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807240"> <div class="moveup"> <div class="ttypography"><p>in E</p> <ul> <li>Card in query i fits constraints on value written on card in left hand in queries with indexes [i,j).</li> </ul><p>i think it's [i,j] isn't it ? Because we have card in i for query j too </p></div> </div> </div> <div class="reply info"> <a class="comment-807240 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807240 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807240"> <li> <div class="comment"> <table class="comment-table" commentId="807271" commentParentId="807240"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TeaTime" style="position: relative;"> <img src='https://userpic.codeforces.org/1199093/avatar/f1cbbd424f7d3cf7.jpg'/> </a> <div><a href="/profile/TeaTime" title="Master TeaTime" class="rated-user user-orange">TeaTime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:25">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807271" href="?#comment-807271" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807240" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807271" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="1199093" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807271"> <div class="moveup"> <div class="ttypography"><p>It's [i, j) because card j was already taken in right hand.</p></div> </div> </div> <div class="reply info"> <a class="comment-807271 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807271 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807271"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807273" commentParentId="807240"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TeaTime" style="position: relative;"> <img src='https://userpic.codeforces.org/1199093/avatar/f1cbbd424f7d3cf7.jpg'/> </a> <div><a href="/profile/TeaTime" title="Master TeaTime" class="rated-user user-orange">TeaTime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807273" href="?#comment-807273" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807240" style="font-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="807273" 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="807273" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="1199093" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807273"> <div class="moveup"> <div class="ttypography"><p>Oh, you are correct, I mistook it with something else. Thanks for noticing!</p><p>Edit: editorial was fixed.</p></div> </div> </div> <div class="reply info"> <a class="comment-807273 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807273 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807273"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807241" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pucuk16" style="position: relative;"> <img src='https://userpic.codeforces.org/1458650/avatar/a688a695b97d78cb.jpg'/> </a> <div><a href="/profile/pucuk16" title="Newbie pucuk16" class="rated-user user-gray">pucuk16</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807241" href="?#comment-807241" style="font-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="807241" 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="807241" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1458650" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807241"> <div class="moveup"> <div class="ttypography"><p>hai.. where my code gone wrong..? please help me..<br /> for problem C <br /> thx <a href="https://codeforces.com/contest/1539/submission/120116110">code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807241"> <li> <div class="comment"> <table class="comment-table" commentId="807335" commentParentId="807241"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bwxnQAQ" style="position: relative;"> <img src='https://userpic.codeforces.org/1816180/avatar/1179db2c2821d194.jpg'/> </a> <div><a href="/profile/bwxnQAQ" title="Expert bwxnQAQ" class="rated-user user-blue">bwxnQAQ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 17:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807335" href="?#comment-807335" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807241" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807335" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="1816180" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807335"> <div class="moveup"> <div class="ttypography"><p>You should check line 37.You change d continuously without initializing.The d on the right side of each formula in line 37 should be the d in line 32 instead of the last calculated d.</p></div> </div> </div> <div class="reply info"> <a class="comment-807335 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807335 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807335"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807251" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spookywooky" style="position: relative;"> <img src='https://userpic.codeforces.org/872585/avatar/a8efaf71cbe05928.jpg'/><img title='Почетный бейдж за поддержку Codeforces на его 10-летие' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/spookywooky" title="Specialist spookywooky" class="rated-user user-cyan">spookywooky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807251" href="?#comment-807251" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807251" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="872585" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807251"> <div class="moveup"> <div class="ttypography"><p>Explanation to E sounds like it would be possible to explain it in an understandable way.</p></div> </div> </div> <div class="reply info"> <a class="comment-807251 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807251 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807251"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807258" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807258" href="?#comment-807258" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807258" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807258"> <div class="moveup"> <div class="ttypography"><p><strong>If there is an item which costs 1, then we will not make the answer worse by buying this item.</strong></p><p>Why is that? For example, consider a situation where we've already bought all items, except for one, and it costs 2, and to make it cost 1 we need to buy 2 more items. In that case it would be cheaper to buy one left item and spend 2 instead of buing two more random items at cost 1 and finally buing one last item, spending 3 in total.</p></div> </div> </div> <div class="reply info"> <a class="comment-807258 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807258 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807258"> <li> <div class="comment"> <table class="comment-table" commentId="807275" commentParentId="807258"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807275" href="?#comment-807275" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807258" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807275" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807275"> <div class="moveup"> <div class="ttypography"><p>In your example you are explicitly making the cost of that item by buying more products of other items. But the statement means that if by buying other items and within limits i.e. less that $$$a_i$$$, then you should buy the items of cost 1.</p></div> </div> </div> <div class="reply info"> <a class="comment-807275 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807275 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807275"> <li> <div class="comment"> <table class="comment-table" commentId="807277" commentParentId="807275"> <tr> <td class="left"> <div style="position: absolute; left: 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/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:54">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807277" href="?#comment-807277" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807277" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807277"> <div class="moveup"> <div class="ttypography"><p>Thanks, that explains it:)</p></div> </div> </div> <div class="reply info"> <a class="comment-807277 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807277 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807277"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807331" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/NoobCpp" style="position: relative;"> <img src='https://userpic.codeforces.org/1716219/avatar/14a123abec8289d0.jpg'/> </a> <div><a href="/profile/NoobCpp" title="Specialist NoobCpp" class="rated-user user-cyan">NoobCpp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 17:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807331" href="?#comment-807331" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807331" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1716219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807331"> <div class="moveup"> <div class="ttypography"><p>Although E and F was more difficult than the rest, the contest was great. First time reach to Expert!!</p><p>Sr about my bad Eng :p</p></div> </div> </div> <div class="reply info"> <a class="comment-807331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807331"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807364" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/livlyf_168" style="position: relative;"> <img src='https://userpic.codeforces.org/1919608/avatar/cf064edf00e3eea6.jpg'/> </a> <div><a href="/profile/livlyf_168" title="Pupil livlyf_168" class="rated-user user-green">livlyf_168</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807364" href="?#comment-807364" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807364" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1919608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807364"> <div class="moveup"> <div class="ttypography"><p>Hey, can anyone help me with problem C. Don't know why is it giving WA on test 10. Below is my submission — <a href="/contest/1539/submission/120223010" title="Посылка 120223010 от livlyf_168">120223010</a>. I have used the same approach, except that I have taken The number of elements required to fill the gap as floor((d-1)/x). </p></div> </div> </div> <div class="reply info"> <a class="comment-807364 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807364 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807364"> <li> <div class="comment"> <table class="comment-table" commentId="807370" commentParentId="807364"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/itish" style="position: relative;"> <img src='https://userpic.codeforces.org/1589684/avatar/d4fea913edfbab4b.jpg'/> </a> <div><a href="/profile/itish" title="Candidate Master itish" class="rated-user user-violet">itish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807370" href="?#comment-807370" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807364" style="font-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="807370" 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="807370" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1589684" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807370"> <div class="moveup"> <div class="ttypography"><p>Change vector(int)split to vector(llint) split and it gets accepted</p></div> </div> </div> <div class="reply info"> <a class="comment-807370 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807370 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807370"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807374" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hotas" style="position: relative;"> <img src='https://userpic.codeforces.org/1150129/avatar/590cdb757ae4763a.jpg'/> </a> <div><a href="/profile/Hotas" title="Newbie Hotas" class="rated-user user-gray">Hotas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807374" href="?#comment-807374" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807374" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1150129" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807374"> <div class="moveup"> <div class="ttypography"><p>Can anyone tell me where am I doing wrong? I am getting wrong answer on test case 10. Problem C. Submission : <a href="/contest/1539/submission/120227942" title="Посылка 120227942 от Hotas">120227942</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807374 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807374 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807374"> <li> <div class="comment"> <table class="comment-table" commentId="807397" commentParentId="807374"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 20:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807397" href="?#comment-807397" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807374" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807397" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807397"> <div class="moveup"> <div class="ttypography"><p>I think the problem is that you have int[] a instead of ll[] a. Each element can be up to 1e18.</p></div> </div> </div> <div class="reply info"> <a class="comment-807397 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807397 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807397"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807378" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/coderaman327" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/coderaman327" title="Expert coderaman327" class="rated-user user-blue">coderaman327</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807378" href="?#comment-807378" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807378" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="886853" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807378"> <div class="moveup"> <div class="ttypography"><p>Can someone please tell me what my mistake is in problem D? <a href="https://codeforces.com/contest/1539/submission/120100696">My submission</a> Thanks in advance!!</p></div> </div> </div> <div class="reply info"> <a class="comment-807378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807378"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807400" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abyboi" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/abyboi" title="Pupil abyboi" class="rated-user user-green">abyboi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 21:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807400" href="?#comment-807400" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807400" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1833158" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807400"> <div class="moveup"> <div class="ttypography"><p>Can someone help me with Problem D? My submission is</p><p><a href="https://codeforces.com/contest/1539/submission/120232784">https://codeforces.com/contest/1539/submission/120232784</a></p><p>Thanks in advance!</p></div> </div> </div> <div class="reply info"> <a class="comment-807400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807400"> <li> <div class="comment"> <table class="comment-table" commentId="807478" commentParentId="807400"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/andr14142" style="position: relative;"> <img src='https://userpic.codeforces.org/620444/avatar/368d81a28bf4f89b.jpg'/> </a> <div><a href="/profile/andr14142" title="Pupil andr14142" class="rated-user user-green">andr14142</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 09:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807478" href="?#comment-807478" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807400" style="font-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="807478" 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="807478" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="620444" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807478"> <div class="moveup"> <div class="ttypography"><p>Your solution has not correct comparison in the case of whole buying goods without discount:<br /> else if (total_bought + products[j].F &lt; products[i].S)<br /> Correct comparison is:<br /> else if (total_bought + products[j].F &lt;= products[i].S)</p></div> </div> </div> <div class="reply info"> <a class="comment-807478 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807478 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807478"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807520" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Madara_Uzumaki" style="position: relative;"> <img src='https://userpic.codeforces.org/1621901/avatar/28eb09a48344e5fb.jpg'/> </a> <div><a href="/profile/Madara_Uzumaki" title="Newbie Madara_Uzumaki" class="rated-user user-gray">Madara_Uzumaki</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 11:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807520" href="?#comment-807520" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807520" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1621901" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807520"> <div class="moveup"> <div class="ttypography"><p>In <strong>problem</strong> C i ran the code in <strong>PyPy3</strong> the code got <strong>TLE in test case 18</strong> but when I ran the same code in <strong>Python3</strong> the code got <strong>accepted</strong> Can anyone clarify why did that happen?</p></div> </div> </div> <div class="reply info"> <a class="comment-807520 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807520 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807520"> <li> <div class="comment"> <table class="comment-table" commentId="807527" commentParentId="807520"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/casul" style="position: relative;"> <img src='https://userpic.codeforces.org/1690955/avatar/21ae0e21fe431dd7.jpg'/> </a> <div><a href="/profile/casul" title="Specialist casul" class="rated-user user-cyan">casul</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 12:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807527" href="?#comment-807527" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807520" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807527" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1690955" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807527"> <div class="moveup"> <div class="ttypography"><p>You may wanna check out this blog:</p><p><a href="https://codeforces.com/blog/entry/82989">https://codeforces.com/blog/entry/82989</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807527 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807527 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807527"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807629" commentParentId="807520"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aberent" 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/aberent" title="Specialist aberent" class="rated-user user-cyan">aberent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 18:13">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807629" href="?#comment-807629" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807520" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807629" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1157884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807629"> <div class="moveup"> <div class="ttypography"><p>I too got some strange behaviour with PyPy3 with test 18. Every version I tried printed a result and then (after it should have finished), got TLE. I wonder whether there is a bug somewhere here. See <a href="https://codeforces.com/blog/entry/92011">my blog entry</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-807629 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807629 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807629"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807566" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zvsevolod" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/zvsevolod" title="Newbie zvsevolod" class="rated-user user-gray">zvsevolod</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 14:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807566" href="?#comment-807566" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807566" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1271216" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807566"> <div class="moveup"> <div class="ttypography"><p>In problem C Java solution with Long[] array gets accepted, but long[] array solution gets TLE. (16th line in both solutions) </p><p>ACC: <a href="https://codeforces.com/contest/1539/submission/120284760">https://codeforces.com/contest/1539/submission/120284760</a> <br /> TLE: <a href="https://codeforces.com/contest/1539/submission/120284797">https://codeforces.com/contest/1539/submission/120284797</a></p><p>Could someone explain me why reference type works faster than primitive in this example?</p></div> </div> </div> <div class="reply info"> <a class="comment-807566 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807566 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807566"> <li> <div class="comment"> <table class="comment-table" commentId="807620" commentParentId="807566"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aberent" 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/aberent" title="Specialist aberent" class="rated-user user-cyan">aberent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 18:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807620" href="?#comment-807620" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807566" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807620" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1157884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807620"> <div class="moveup"> <div class="ttypography"><p>Apparently Java uses different sorting algorithms for integers (including longs) and objects. The algorithm for integers is generally faster, but its worst case is worse. You might have simply been unlucky. See the implementation notes for the two versions of sort: <a href="https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(long%5B%5D">https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(long%5B%5D</a>) <a href="https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(java.lang.Object%5B%5D">https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(java.lang.Object%5B%5D</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-807620 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807620 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807620"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807726" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/quinoa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/quinoa" title="Expert quinoa" class="rated-user user-blue">quinoa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 23:40">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807726" href="?#comment-807726" style="font-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="807726" 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="807726" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="592293" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807726"> <div class="moveup"> <div class="ttypography"><p>I had a hard time understanding the tutorial for problem E. This is my attempt at making it easier to understand.</p><p><strong>Easier problem: jump game</strong></p><p>Consider <a href="https://leetcode.com/problems/jump-game/">this</a> easier problem: you have an array $$$x$$$ where $$$x[i]$$$ means what the farthest is that you can jump from position $$$i$$$. Is it possible to reach the last element in the array if you start from position 0?</p><p>We can solve it with a DP where $$$dp[i]$$$ = can we reach the end if we start from position i? The solution to the problem is then equal to $$$dp[0]$$$. The transitions are like this: $$$dp[i]$$$ = $$$dp[i + 1]$$$ $$$||$$$ $$$dp[i + 2]$$$ $$$||$$$ ... $$$||$$$ $$$dp[i + x[i]]$$$. There are $$$N$$$ states and the transitions are $$$O(N)$$$ so this runs in $$$O(N^2)$$$.</p><p>We can make every transition $$$O(1)$$$ with a greedy insight. Instead of checking $$$dp[i + 1]$$$, ..., $$$dp[i + x[i]]$$$ we only need to check $$$dp[j]$$$ where $$$j$$$ is the leftmost position from which we can reach the end. The reason this works is that the leftmost position from which we can reach the end has the best probability of being within our jumping range. We can keep track of this leftmost position as we compute each state in a bottom up fashion.</p> <pre><code>int leftmost_possible = N - 1; for (int i = N - 2; i &gt;= 0; --i) { if (leftmost_possible &lt;= i + x[i]) { dp[i] = true; leftmost_possible = i; } } </code></pre><p><strong>Back to problem E</strong></p><p>We can again solve this with an $$$O(N^2)$$$ DP where $$$dp(x, y)$$$ = can we finish if card with index $$$x$$$ is in the left hand, and card with index $$$y$$$ is in the right hand (and we have just answered query $$$max(x, y)$$$). </p><p>We can notice that we can reduce the number of states to $$$N$$$. Because if we are at $$$dp(x, y)$$$ (WLOG $$$x &gt; y$$$) then</p> <ul> <li>either we will keep replacing the card in the left hand until we reach the end</li> <li>or at some point we have to take something in the right hand and we transition to state $$$dp(k, k + 1)$$$</li> </ul><p>So if we are at state (x, y) then in the next step either we are done, or we will transition to $$$dp(k, k + 1)$$$. Therefore (since we start at state $$$dp(0, 1)$$$) we will only visit states of the type $$$dp(k, k + 1)$$$ (and $$$dp(k - 1, k)$$$), and there are only $$$O(N)$$$ of those.</p><p>The transition is now $$$O(N)$$$ because we have to consider every $$$k$$$ such that $$$dp(k, k + 1)$$$ works. But with the same greedy insight as in the jump game problem we can reduce that to $$$O(1)$$$. Again we can store &quot;the leftmost k that works&quot; as we compute the states and therefore we can find the transition in $$$O(1)$$$.</p><p>Now of course in this problem another hard part is to compute the &quot;maximum jump length&quot; at every position. In the jump game problem this was given in the input, whereas here we have to compute it. For sure you can do it in logarithmic time with a segment tree (I saw it in <a href="https://www.youtube.com/watch?v=seaskdKf2sI">Colin Galen's video</a>). But apparently you can also do it in $$$O(1)$$$ since the solution runs in O(N) according to the tutorial. I didn't think about optimizing that part yet.</p></div> </div> </div> <div class="reply info"> <a class="comment-807726 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807726 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807726"> <li> <div class="comment"> <table class="comment-table" commentId="852194" commentParentId="807726"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ahshafi" style="position: relative;"> <img src='https://userpic.codeforces.org/818506/avatar/d65d006cfdce087a.jpg'/> </a> <div><a href="/profile/ahshafi" title="Candidate Master ahshafi" class="rated-user user-violet">ahshafi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/19/2021 17:24">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-852194" href="?#comment-852194" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807726" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="852194" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="818506" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-852194"> <div class="moveup"> <div class="ttypography"><p>me too confused about how to compute maximum jump length in O(1) </p></div> </div> </div> <div class="reply info"> <a class="comment-852194 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-852194 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-852194"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808157" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sg55" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sg55" title="Newbie sg55" class="rated-user user-gray">sg55</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/24/2021 05:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808157" href="?#comment-808157" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808157" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1445980" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808157"> <div class="moveup"> <div class="ttypography"><p>I have used 2 the same method as used by most of the other coders but my code is giving tle. Can please someone look and tell me why it is? <a href="/contest/1539/submission/120407076" title="Посылка 120407076 от sg55">120407076</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808157 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808157 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808157"> <li> <div class="comment"> <table class="comment-table" commentId="808253" commentParentId="808157"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zvsevolod" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/zvsevolod" title="Newbie zvsevolod" class="rated-user user-gray">zvsevolod</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/24/2021 13:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808253" href="?#comment-808253" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808157" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808253" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1271216" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808253"> <div class="moveup"> <div class="ttypography"><p>Try to use Long[] array instead of long[]. Also you may read my comment above.</p></div> </div> </div> <div class="reply info"> <a class="comment-808253 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808253 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808253"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hritik27" style="position: relative;"> <img src='https://userpic.codeforces.org/1232410/avatar/af014e1c10ef2a19.jpg'/> </a> <div><a href="/profile/hritik27" title="Newbie hritik27" class="rated-user user-gray">hritik27</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/24/2021 19:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808320" href="?#comment-808320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808320" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1232410" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808320"> <div class="moveup"> <div class="ttypography"><p>Can someone please help me with problem A?? Can't understand the solution give.</p></div> </div> </div> <div class="reply info"> <a class="comment-808320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808320"> <li> <div class="comment"> <table class="comment-table" commentId="810306" commentParentId="808320"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/songzy12" style="position: relative;"> <img src='https://userpic.codeforces.org/249570/avatar/3c83a5ef255ff4d6.jpg'/> </a> <div><a href="/profile/songzy12" title="Pupil songzy12" class="rated-user user-green">songzy12</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/30/2021 17:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810306" href="?#comment-810306" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808320" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810306" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="249570" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810306"> <div class="moveup"> <div class="ttypography"><p>1. First consider the case where there are infinite participants. Then each participant would be disturbed by $$$t/x$$$ participants following him. </p><p>2. Then consider the case that $$$n$$$ is finite but large enough, then the first participant would be disturbed by $$$t/x$$$, the same for participant 2, ..., until $$$k$$$. </p><p>For the participants beyond k, the number of participants that would disturb them are decreased by 1 each time, i.e., $$$t/x - 1$$$, $$$t/x - 2$$$, until 0 for the last participant.</p><p>There are $$$t/x$$$ numbers from $$$t/x - 1$$$ until 0, thus we know $$$k = n - t/x$$$.</p><p>So the answer would be $$$(n-t/x) * (t/x) + (t/x-1)*(t/x)/2$$$.</p><p>3. The $$$min$$$ and $$$max$$$ in the answer is to solve the case where n is not large enough, i.e., when $$$n &lt; t/x$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-810306 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810306 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810306"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808360" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/augurar" style="position: relative;"> <img src='https://userpic.codeforces.org/391071/avatar/8a814e47f9aacb44.jpg'/> </a> <div><a href="/profile/augurar" title="Expert augurar" class="rated-user user-blue">augurar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 02:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808360" href="?#comment-808360" style="font-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="808360" 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="808360" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="391071" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808360"> <div class="moveup"> <div class="ttypography"><p>I'm glad I didn't participate in this one officially. Problem C was easy but I kept getting a TLE for stupid language-specific reasons:</p> <ul> <li><p>My <a href="https://codeforces.com/contest/1539/submission/120478273">Python solution</a> got TLE on test 18 with PyPy3, but the same code passed with Python 3.</p></li> <li><p>My <a href="https://codeforces.com/contest/1539/submission/120478521">Java solution</a> got TLE on test 61, but passed if I changed <code>long[]</code> to <code>Long[]</code>. (This is kind of my fault for not knowing Java uses a worst-case O(n^2) sort for primitive arrays.)</p></li> <li><p>My <a href="https://codeforces.com/contest/1539/submission/120480356">C++ solution</a> passed with no special optimization.</p></li> </ul><p>In my opinion that's an indication that the time limit is overly strict, especially for an ABC problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-808360 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808360 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808360"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="816645" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/comseung18_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/comseung18_" title="Expert comseung18_" class="rated-user user-blue">comseung18_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/15/2021 09:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-816645" href="?#comment-816645" style="font-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="816645" 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="816645" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275870" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-816645"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1539/submission/122552751" title="Посылка 122552751 от comseung18_">122552751</a> why my solution A is not correct ? ans1 is Editorial solution ans2 is my solution</p><p>I checked my ans2 in many times. but ans1 equals ans2..<br />~~~~~ import random k = int(input()) for _ in range(k): n = random.randint(1,2*1000000000) x = random.randint(1,2*1000000000) t = random.randint(1,2*1000000000) tmp = t//x ans1 = max(0,n-tmp)*tmp + min(n-1,tmp-1)*min(n,tmp)//2 ans2 = tmp*n — tmp*tmp + tmp*n — ((2*n-tmp+1)*tmp)//2 if ans1 != ans2: print(ans1,ans2) ~~~~~</p></div> </div> </div> <div class="reply info"> <a class="comment-816645 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-816645 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-816645"> <li> <div class="comment"> <table class="comment-table" commentId="816647" commentParentId="816645"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/comseung18_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/comseung18_" title="Expert comseung18_" class="rated-user user-blue">comseung18_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/15/2021 09:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-816647" href="?#comment-816647" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-816645" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="816647" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275870" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-816647"> <div class="moveup"> <div class="ttypography"><p>when , t/x &gt; n , ans2 is wrong sorry</p></div> </div> </div> <div class="reply info"> <a class="comment-816647 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-816647 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-816647"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="984743" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PrickyToTheMoon" style="position: relative;"> <img src='https://userpic.codeforces.org/1432360/avatar/422cb9d88c769b8d.jpg'/> </a> <div><a href="/profile/PrickyToTheMoon" title="Pupil PrickyToTheMoon" class="rated-user user-green">PrickyToTheMoon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/24/2022 21:10">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-984743" href="?#comment-984743" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="984743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1432360" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-984743"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1539/submission/186604051" title="Submission 186604051 by PrickyToTheMoon">186604051</a></p><p>Please help. Cannot understand why getting WA on test case 18. My approach matches perfectly with editorial.</p><p>Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-984743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-984743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-984743"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="995447" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mohsina_Shaikh" style="position: relative;"> <img src='https://userpic.codeforces.org/1396580/avatar/6f21616a2d8d578.jpg'/> </a> <div><a href="/profile/Mohsina_Shaikh" title="Newbie Mohsina_Shaikh" class="rated-user user-gray">Mohsina_Shaikh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/25/2023 07:37">8 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-995447" href="?#comment-995447" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="995447" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1396580" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-995447"> <div class="moveup"> <div class="ttypography"><p>can anyone please explain how problem B can be solved using DP.</p></div> </div> </div> <div class="reply info"> <a class="comment-995447 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-995447 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-995447"> </ul> </div> <br/> <div id="editBox-100475" 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 firstPreview100475 = true; var lastPreviewContent100475 = ''; 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=100475] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=100475] 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-92516").click(function () { $.post("/data/topic/vote", {topicId: 92516, _tta: Codeforces.tta(), topicRevisionId: 229854, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-92516").click(function () { $.post("/data/topic/vote", {topicId: 92516, _tta: Codeforces.tta(), topicRevisionId: 229854, 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:33:26</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:'81289365b9230c42',t:'MTY5NjcwNzIwNi44NDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1539F
1539
F
ru
F. Необычный массив
<div class="problem-statement"><div class="header"><div class="title">F. Необычный массив</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Васи есть массив, состоящий из $$$n$$$ чисел $$$a_1, a_2, \ldots, a_n$$$. Каждое число в этом массиве Вася считает по-своему необычным. Чтобы вычислить необычность числа на позиции $$$i$$$, Вася делает следующее:</p><p>Он выбирает подотрезок $$$a_l, a_{l+1}, \ldots, a_r$$$ такой, что $$$1 \le l \le i \le r \le n$$$ и мысленно сортирует его по возрастанию (равные элементы он может переставлять так, как ему хочется). Далее на этом подотрезке он находит центр. Центром подотрезка называется элемент на позиции $$$(l + r) / 2$$$, если длина отрезка нечётна, или элемент на позиции $$$(l + r + 1) / 2$$$, если длина отрезка чётна. Теперь Вася находит на этом подотрезеке элемент, который до сортировки стоял на позиции $$$i$$$, и смотрит на расстояние от этого элемента до центра подотрезка (расстояние между элементами с индексами $$$j$$$ и $$$k$$$ равняется $$$|j - k|$$$).</p><p>Необычностью числа на позиции $$$i$$$ называется максимальное такое расстояние среди всех подходящих выборов $$$l$$$ и $$$r$$$.</p><p>Вася хочет посчитать необычность каждого числа в своём массиве. Помогите ему это сделать.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных находится одно целое число $$$n$$$ ($$$1 \le n \le 200\,000$$$) — размер массива.</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — сам массив.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В единственной строке выведите $$$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> 5 5 4 3 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 1 2 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 3 6 5 6 2 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 1 3 2 3 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере:</p><ol><li> Для первой позиции подойдёт отрезок от позиции $$$1$$$ до позиции $$$5$$$. Если его отсортировать, то числа упорядочатся по значению как $$$[1, 2, 3, 4, 5]$$$, центр будет равен $$$3$$$, таким образом расстояние от центра до числа $$$5$$$ равно $$$2$$$.</li><li> Для второй позиции подойдёт отрезок от позиции $$$2$$$ до позиции $$$4$$$.</li><li> Для третей позиции подойдёт отрезок от позиции $$$3$$$ до позиции $$$5$$$.</li><li> Для четвёртой позиции подойдёт отрезок от позиции $$$1$$$ до позиции $$$4$$$. Если его отсортировать, то числа упорядочатся по значению как $$$[2, 3, 4, 5]$$$, центр будет равен $$$4$$$, таким образом расстояние от центра до числа $$$2$$$ равно $$$2$$$. </li><li> Для пятой позиции подойдёт отрезок от позиции $$$1$$$ до позиции $$$5$$$.</li></ol></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="cb8681d10483f668c58e88ac745bb8e7"/> <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="3b3d6aa18ec7f2c8636f747ba32c1b3c7997564d"/> <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='cb8681d10483f668c58e88ac745bb8e7'>&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%2F1539%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='cb8681d10483f668c58e88ac745bb8e7'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1539">Codeforces Round 727 (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='cb8681d10483f668c58e88ac745bb8e7'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1539/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения"> сортировки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *2600 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='cb8681d10483f668c58e88ac745bb8e7'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1021675"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='cb8681d10483f668c58e88ac745bb8e7'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1021675"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/91905" title="Codeforces Round #727 (Div. 2, по Всероссийской олимпиаде имени Келдыша) [Рейтинговый]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13910:13911" 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/91906" title="tutorial" target="_blank">tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13923" 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/1539">Задачи</a></li> <li><a href="/contest/1539/submit">Отослать</a></li> <li><a href="/contest/1539/my">Мои посылки</a></li> <li><a href="/contest/1539/status">Статус</a></li> <li><a href="/contest/1539/hacks">Взломы</a></li> <li><a href="/contest/1539/room/1">Комната</a></li> <li><a href="/contest/1539/standings">Положение</a></li> <li><a href="/contest/1539/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2929f16a9f2958fadaf67a76f6a04ef034ad741f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ чисел $$$a_1, a_2, \ldots, a_n$$$. Каждое число в этом массиве Вася считает по-своему необычным. Чтобы вычислить необычность числа на позиции $$$i$$$, Вася делает следующее:</p><p>Он выбирает подотрезок $$$a_l, a_{l+1}, \ldots, a_r$$$ такой, что $$$1 \le l \le i \le r \le n$$$ и мысленно сортирует его по возрастанию (равные элементы он может переставлять так, как ему хочется). Далее на этом подотрезке он находит центр. Центром подотрезка называется элемент на позиции $$$(l + r) / 2$$$, если длина отрезка нечётна, или элемент на позиции $$$(l + r + 1) / 2$$$, если длина отрезка чётна. Теперь Вася находит на этом подотрезеке элемент, который до сортировки стоял на позиции $$$i$$$, и смотрит на расстояние от этого элемента до центра подотрезка (расстояние между элементами с индексами $$$j$$$ и $$$k$$$ равняется $$$|j - k|$$$).</p><p>Необычностью числа на позиции $$$i$$$ называется максимальное такое расстояние среди всех подходящих выборов $$$l$$$ и $$$r$$$.</p><p>Вася хочет посчитать необычность каждого числа в своём массиве. Помогите ему это сделать.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных находится одно целое число $$$n$$$ ($$$1 \le n \le 200\,000$$$) — размер массива.</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — сам массив.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В единственной строке выведите $$$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> 5 5 4 3 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 1 2 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 3 6 5 6 2 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 1 3 2 3 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере:</p><ol><li> Для первой позиции подойдёт отрезок от позиции $$$1$$$ до позиции $$$5$$$. Если его отсортировать, то числа упорядочатся по значению как $$$[1, 2, 3, 4, 5]$$$, центр будет равен $$$3$$$, таким образом расстояние от центра до числа $$$5$$$ равно $$$2$$$.</li><li> Для второй позиции подойдёт отрезок от позиции $$$2$$$ до позиции $$$4$$$.</li><li> Для третей позиции подойдёт отрезок от позиции $$$3$$$ до позиции $$$5$$$.</li><li> Для четвёртой позиции подойдёт отрезок от позиции $$$1$$$ до позиции $$$4$$$. Если его отсортировать, то числа упорядочатся по значению как $$$[2, 3, 4, 5]$$$, центр будет равен $$$4$$$, таким образом расстояние от центра до числа $$$2$$$ равно $$$2$$$. </li><li> Для пятой позиции подойдёт отрезок от позиции $$$1$$$ до позиции $$$5$$$.</li></ol></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c6b5ef669da5',t:'MTY5NjY2NzM2NC44NTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2600"]
https://codeforces.com/blog/entry/91906
<!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="c4ae3f1dbdd3aa7685e27f571fc144d8"/> <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="Codeforces Round #727 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #727 Editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='c4ae3f1dbdd3aa7685e27f571fc144d8'>&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%2F91906">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='c4ae3f1dbdd3aa7685e27f571fc144d8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:31:34</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:31:34</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='c4ae3f1dbdd3aa7685e27f571fc144d8'/> <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="92516"> <div class="title"> <a href="/blog/entry/91906"> <p>Codeforces Round #727 Editorial</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="Jun/18/2021 00:11">2 years ago</span>, translation, <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/1539/problem/A" title="Codeforces Round 727 (Div. 2)">1539A - Contest Start</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/1539/problem/B" title="Codeforces Round 727 (Div. 2)">1539B - Love Song</a> was authored by jury and prepared by <a class="rated-user user-red" href="/profile/talant" title="Grandmaster talant">talant</a></p><p><a href="/contest/1539/problem/C" title="Codeforces Round 727 (Div. 2)">1539C - Stable Groups</a> was authored by <a class="rated-user user-orange" href="/profile/Artyom123" title="International Master Artyom123">Artyom123</a> and prepared by <a class="rated-user user-orange" href="/profile/Artyom123" title="International Master Artyom123">Artyom123</a> and <a class="rated-user user-blue" href="/profile/shishyando" title="Expert shishyando">shishyando</a></p><p><a href="/contest/1539/problem/D" title="Codeforces Round 727 (Div. 2)">1539D - PriceFixed</a> was authored by Helen Andreeva and prepared by <a class="rated-user user-red" href="/profile/Siberian" title="Grandmaster Siberian">Siberian</a></p><p><a href="/contest/1539/problem/E" title="Codeforces Round 727 (Div. 2)">1539E - Game with Cards</a> was authored and prepared by <a class="rated-user user-orange" href="/profile/TeaTime" title="Master TeaTime">TeaTime</a></p><p><a href="/contest/1539/problem/F" title="Codeforces Round 727 (Div. 2)">1539F - Strange Array</a> was authored and prepared by <a class="rated-user user-orange" href="/profile/Tikhon228" title="Master Tikhon228">Tikhon228</a></p> <div class="problemTutorial" problemcode="1539A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539C">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539D">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539E">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1539F">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/1539" class="notice" style="text-decoration: none;">Codeforces Round 727 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-42191-92516").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: "91906", 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> <span style="padding: 0 0.35em;"> <a href="/search?query=%23727" class="tag notice" style="text-decoration: none;">#727</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-92516"><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'>+79</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-92516"><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="Jun/18/2021 00:11">2 years ago</span> </li> <li> <a href="/blog/entry/91906#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/91906#comments"> 116 </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="100475"> <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 (81)</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="807107" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hhoppitree" style="position: relative;"> <img src='https://userpic.codeforces.org/1366950/avatar/874468310bfb5ee5.jpg'/> </a> <div><a href="/profile/hhoppitree" title="Grandmaster hhoppitree" class="rated-user user-red">hhoppitree</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 01:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807107" href="?#comment-807107" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807107" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1366950" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807107"> <div class="moveup"> <div class="ttypography"><p>A great competition with hacking :)</p></div> </div> </div> <div class="reply info"> <a class="comment-807107 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807107 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807107"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807116" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/iLoveIOI" style="position: relative;"> <img src='https://userpic.codeforces.org/483613/avatar/19b4d34a35f1e022.jpg'/> </a> <div><a href="/profile/iLoveIOI" title="Master iLoveIOI" class="rated-user user-orange">iLoveIOI</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 03:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807116" href="?#comment-807116" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807116" class="CommentVoteFrame" data-commentRating="34" data-commentUserId="483613" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+34</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807116"> <div class="moveup"> <div class="ttypography"><p>Can someone explain one of the multiset solutions to E? Thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-807116 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807116 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807116"> <li> <div class="comment"> <table class="comment-table" commentId="807421" commentParentId="807116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lazywitt" style="position: relative;"> <img src='https://userpic.codeforces.org/995139/avatar/e4276e734c1b167e.jpg'/> </a> <div><a href="/profile/lazywitt" title="Pupil lazywitt" class="rated-user user-green">lazywitt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 21:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807421" href="?#comment-807421" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807116" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807421" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="995139" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807421"> <div class="moveup"> <div class="ttypography"><p>Can you show any multiset solutions which passed ? </p></div> </div> </div> <div class="reply info"> <a class="comment-807421 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807421 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807421"> <li> <div class="comment"> <table class="comment-table" commentId="807448" commentParentId="807421"> <tr> <td class="left"> <div style="position: absolute; left: 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/iLoveIOI" style="position: relative;"> <img src='https://userpic.codeforces.org/483613/avatar/19b4d34a35f1e022.jpg'/> </a> <div><a href="/profile/iLoveIOI" title="Master iLoveIOI" class="rated-user user-orange">iLoveIOI</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 04:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807448" href="?#comment-807448" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807421" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807448" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="483613" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807448"> <div class="moveup"> <div class="ttypography"><p>For example, <a href="https://codeforces.com/contest/1539/submission/120110352">this</a> and <a href="https://codeforces.com/contest/1539/submission/120092916">this</a>. </p></div> </div> </div> <div class="reply info"> <a class="comment-807448 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807448 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807448"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807484" commentParentId="807116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lucaperju" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lucaperju" title="International Grandmaster lucaperju" class="rated-user user-red">lucaperju</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 09:45">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807484" href="?#comment-807484" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807116" style="font-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="807484" 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="807484" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="627011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807484"> <div class="moveup"> <div class="ttypography"><p>Consider dpL[i][j] (different from the one from the editorial) as equal to 1 if it's possible to take the first i cards, ith one in the left hand, and j being the last card we took in the right hand (j&lt;i). And, dpR[j][i] as equal to 1 if it's possible to take the first i cards, last one in the right hand, and j being the last card we took in the left hand. then, instead of storing the whole array, let L[i] be a set (or multiset) of pairs of &lt;k[j],j&gt; such that dpL[i][j] is 1, (and the same for R[i]). Now, if we're at step i and know L[i] and R[i], let's try to compute L[i+1] and R[i+1]: Let's focus on computing L[i+1], for R[i+1] it's similar: if (i+1)th card can't go in the left hand, then L[i+1] will be empty, let's assume it can go there. Let's also assume that the (i+1)th right hand can take any card, we'll fix that later. Then, first of all, if the set R[i] is not empty, we should add the pair &lt;k[i],i&gt; to L[i+1], that's because we can go from having the cards from (j, i) to (i+1, i) by taking the i+1th card in the left hand. And, let's also add to L[i+1] all the pairs from L[i], because we can get those by going from (i, j) to (i+1, j). Now, I assumed that the (i+1)th right hand can take any card, while in reality it can only take those whose k is between ar[i+1] and br[i+1]. So, let's erase from L[i+1] the pairs that are not valid. Since it's a set, we can just erase the smallest card values and the highest card values from the set which are not in the interval. This might seem like it's too slow, but it's actually amortized, because at each step, we only add at most one new pair to the set ( the pair &lt;k[i], i&gt; ), and delete some of the pairs which aren't valid. I'm not sure if I explained this very well, I hope it's clear.</p></div> </div> </div> <div class="reply info"> <a class="comment-807484 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807484 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807484"> <li> <div class="comment"> <table class="comment-table" commentId="807490" commentParentId="807484"> <tr> <td class="left"> <div style="position: absolute; left: 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/iLoveIOI" style="position: relative;"> <img src='https://userpic.codeforces.org/483613/avatar/19b4d34a35f1e022.jpg'/> </a> <div><a href="/profile/iLoveIOI" title="Master iLoveIOI" class="rated-user user-orange">iLoveIOI</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 10:26">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807490" href="?#comment-807490" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807484" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807490" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="483613" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807490"> <div class="moveup"> <div class="ttypography"><p>Ah, I see thanks a lot! It was very clear :)</p></div> </div> </div> <div class="reply info"> <a class="comment-807490 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807490 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807490"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807916" commentParentId="807484"> <tr> <td class="left"> <div style="position: absolute; left: 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/Mrajaryan" style="position: relative;"> <img src='https://userpic.codeforces.org/1377953/avatar/e904b3a3a2eac1ad.jpg'/> </a> <div><a href="/profile/Mrajaryan" title="Newbie Mrajaryan" class="rated-user user-gray">Mrajaryan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 13:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807916" href="?#comment-807916" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807484" style="font-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="807916" 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="807916" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1377953" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807916"> <div class="moveup"> <div class="ttypography"><p>Thanks for explanation. But I can't understand why I should use dp? Can you please give some idea on this ? Or just tell me the naive approach by which i can solve the problem? Like naive dp approach</p></div> </div> </div> <div class="reply info"> <a class="comment-807916 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807916 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807916"> <li> <div class="comment"> <table class="comment-table" commentId="807995" commentParentId="807916"> <tr> <td class="left"> <div style="position: absolute; left: 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/lucaperju" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/lucaperju" title="International Grandmaster lucaperju" class="rated-user user-red">lucaperju</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 17:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807995" href="?#comment-807995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807916" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807995" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="627011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807995"> <div class="moveup"> <div class="ttypography"><p>A naive dp approach using the same dp I described above would be: dpL[i][j] (j&lt;i) is true if, obviously, ith card can stay in the left hand (at step i), and jth card can stay in the right hand (at step i), and either:</p> <ul> <li><p>j &lt; (i-1), and dpL[i-1][j] is true</p></li> <li><p>OR j == (i-1), and there exists such k &lt; (i-1) so that dpR[k][i-1] is true</p></li> </ul><p>And similarly for dpR. After calculating this, you can easily recreate the solution from right to left.</p></div> </div> </div> <div class="reply info"> <a class="comment-807995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807995"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="810899" commentParentId="807484"> <tr> <td class="left"> <div style="position: absolute; left: 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/vishaaaal" style="position: relative;"> <img src='https://userpic.codeforces.org/1443354/avatar/25a2dd924894eeeb.jpg'/> </a> <div><a href="/profile/vishaaaal" title="Expert vishaaaal" class="rated-user user-blue">vishaaaal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/02/2021 20:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810899" href="?#comment-810899" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807484" style="font-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="810899" 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="810899" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1443354" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-810899"> <div class="moveup"> <div class="ttypography"><p>How will the following be represented according to these dp states?</p><p>We can pick all the cards upto the ith card in the left hand but none of them in the right hand (in other words, all the queries are answered on the left hand upto the ith card). </p><p>This would imply that there is no j such that dpL[i][j] is 1. But still we can answer all the queries upto the ith card.</p><p>Edit: I thought a lil bit about it and I think we can use 0 as a dummy card (which basically means, by default we'll have 0 as a card in right hand if we don't pick any card in it). And yess, AC. Great explanation OFZ.</p></div> </div> </div> <div class="reply info"> <a class="comment-810899 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810899 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810899"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807117" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Acfboy" style="position: relative;"> <img src='https://userpic.codeforces.org/873793/avatar/146c53315bccb6e9.jpg'/> </a> <div><a href="/profile/Acfboy" title="Master Acfboy" class="rated-user user-orange">Acfboy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 03:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807117" href="?#comment-807117" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807117" class="CommentVoteFrame" data-commentRating="61" data-commentUserId="873793" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+61</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807117"> <div class="moveup"> <div class="ttypography"><p>Nice problems, but the gap between problem ABCD and EF seems too large.</p></div> </div> </div> <div class="reply info"> <a class="comment-807117 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807117 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807117"> <li> <div class="comment"> <table class="comment-table" commentId="807121" commentParentId="807117"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807121" href="?#comment-807121" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807117" style="font-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="807121" 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="807121" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807121"> <div class="moveup"> <div class="ttypography"><p>I think there is a mistake in the editorial of the Problem F.</p><p>The editorial said if the $$$a_i$$$ is less than or equal to the median element then $$$ans = \left\lfloor\dfrac{cnt_R+cnt_M-cnt_L+1}{2} \right\rfloor$$$, but if I have an array that is $$$[1, 2, 3, 4, 4, 6]$$$, the ans of the number $$$4$$$ should be 1, and if you use the formula mentioned above, you may get a wrong answer 0.</p><p>Could anyone tell me the correct formula?</p></div> </div> </div> <div class="reply info"> <a class="comment-807121 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807121 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807121"> <li> <div class="comment"> <table class="comment-table" commentId="807156" commentParentId="807121"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807156" href="?#comment-807156" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807121" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807156" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807156"> <div class="moveup"> <div class="ttypography"><p>The formula is correct, but it's for when the element come to the left of median. When element comes to right of median, other formula should be used which should give you 1. That's why we should take maximum from left &amp; right.</p></div> </div> </div> <div class="reply info"> <a class="comment-807156 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807156 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807156"> <li> <div class="comment"> <table class="comment-table" commentId="807196" commentParentId="807156"> <tr> <td class="left"> <div style="position: absolute; left: 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/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807196" href="?#comment-807196" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807156" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807196" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807196"> <div class="moveup"> <div class="ttypography"><p>Thank you very much. You're right and I have solved this problem by using two distinct formulas. </p></div> </div> </div> <div class="reply info"> <a class="comment-807196 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807196 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807196"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807159" commentParentId="807121"> <tr> <td class="left"> <div style="position: absolute; left: 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/Ka1hatsu" style="position: relative;"> <img src='https://userpic.codeforces.org/761494/avatar/5d5b8ffd577a29a8.jpg'/> </a> <div><a href="/profile/Ka1hatsu" title="Pupil Ka1hatsu" class="rated-user user-green">Ka1hatsu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807159" href="?#comment-807159" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807121" style="font-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="807159" 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="807159" class="CommentVoteFrame" data-commentRating="-6" data-commentUserId="761494" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807159"> <div class="moveup"> <div class="ttypography"><p>sorry</p></div> </div> </div> <div class="reply info"> <a class="comment-807159 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807159 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807159"> <li> <div class="comment"> <table class="comment-table" commentId="807192" commentParentId="807159"> <tr> <td class="left"> <div style="position: absolute; left: 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/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807192" href="?#comment-807192" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807159" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807192" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807192"> <div class="moveup"> <div class="ttypography"><p>I'm sorry but the median number is 4 according to the Problem F.</p></div> </div> </div> <div class="reply info"> <a class="comment-807192 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807192 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807192"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807120" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/highighiq" style="position: relative;"> <img src='https://userpic.codeforces.org/1420719/avatar/97be0e366e499727.jpg'/> </a> <div><a href="/profile/highighiq" title="Master highighiq" class="rated-user user-orange">highighiq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807120" href="?#comment-807120" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807120" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="1420719" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807120"> <div class="moveup"> <div class="ttypography"><p>Good problems!(But E,F is too difficult!) And I get to expert!</p></div> </div> </div> <div class="reply info"> <a class="comment-807120 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807120 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807120"> <li> <div class="comment"> <table class="comment-table" commentId="807122" commentParentId="807120"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Little-aztl" style="position: relative;"> <img src='https://userpic.codeforces.org/824342/avatar/31c31cc6261e1408.jpg'/> </a> <div><a href="/profile/Little-aztl" title="Expert Little-aztl" class="rated-user user-blue">Little-aztl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807122" href="?#comment-807122" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807120" style="font-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="807122" 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="807122" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="824342" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807122"> <div class="moveup"> <div class="ttypography"><p>Congratulations!</p></div> </div> </div> <div class="reply info"> <a class="comment-807122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807122"> <li> <div class="comment"> <table class="comment-table" commentId="807125" commentParentId="807122"> <tr> <td class="left"> <div style="position: absolute; left: 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/highighiq" style="position: relative;"> <img src='https://userpic.codeforces.org/1420719/avatar/97be0e366e499727.jpg'/> </a> <div><a href="/profile/highighiq" title="Master highighiq" class="rated-user user-orange">highighiq</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:12">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807125" href="?#comment-807125" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807122" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807125" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1420719" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807125"> <div class="moveup"> <div class="ttypography"><p>thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-807125 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807125 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807125"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807124" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hithu" style="position: relative;"> <img src='https://userpic.codeforces.org/202138/avatar/c537257b9e17f402.jpg'/> </a> <div><a href="/profile/hithu" title="Pupil hithu" class="rated-user user-green">hithu</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:09">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807124" href="?#comment-807124" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="202138" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807124"> <div class="moveup"> <div class="ttypography"><p>Still don't understand editorial of D, can anybody explain the two pointer technique?</p></div> </div> </div> <div class="reply info"> <a class="comment-807124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807124"> <li> <div class="comment"> <table class="comment-table" commentId="807128" commentParentId="807124"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Enigma20" style="position: relative;"> <img src='https://userpic.codeforces.org/1301418/avatar/3ba73a2cb1eeb8ef.jpg'/> </a> <div><a href="/profile/Enigma20" title="Expert Enigma20" class="rated-user user-blue">Enigma20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807128" href="?#comment-807128" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807124" style="font-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="807128" 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="807128" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="1301418" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807128"> <div class="moveup"> <div class="ttypography"><p>First we sort the array according to increasing order of $$$b_i$$$. Now, we maintain 2 pointers one at the start of the array(say $$$i$$$) and other one at the end(say $$$j$$$). Also, let's maintain two variables $$$cur$$$(stores number of products already taken), $$$ans$$$(stores the required answer).</p><p>Now, we run a loop until $$$i\leq j$$$.</p><p>If $$$cur\geq b_i$$$, there is no point to leave this product, so we buy all $$$a_i$$$ products with 50% discount and update our $$$cur$$$ and $$$ans$$$.</p><p>If $$$cur\lt b_i$$$, then we start from second pointer i.e. $$$j$$$ and keep taking $$$min(b_i-cur,a_j)$$$ products for 2 rubles, if $$$cur\lt b_j$$$, otherwise for 1 ruble. We stop once we have $$$cur\geq b_i$$$. Update $$$cur,ans,a_j$$$ accordingly. If $$$a_j=0$$$, decrement $$$j$$$.</p><p><a href="https://codeforces.com/contest/1539/submission/120108298">My submission</a></p><p>In this submission, I ran a loop until $$$i\lt j$$$ and checked $$$i=j$$$ condition separately but that isn't necessary.</p></div> </div> </div> <div class="reply info"> <a class="comment-807128 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807128 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807128"> <li> <div class="comment"> <table class="comment-table" commentId="807155" commentParentId="807128"> <tr> <td class="left"> <div style="position: absolute; left: 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/crozzhtt" style="position: relative;"> <img src='https://userpic.codeforces.org/1592985/avatar/ea9a2bfb02b015fb.jpg'/> </a> <div><a href="/profile/crozzhtt" title="Newbie crozzhtt" class="rated-user user-gray">crozzhtt</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807155" href="?#comment-807155" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807128" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807155" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1592985" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807155"> <div class="moveup"> <div class="ttypography"><p>but when cur &lt; bi I wonder if I can choose to continue buying (i-1)th product for 1 ruble or buying j-th product for 2 rubles. Will the 2nd option be more optimal than the 1st option?</p></div> </div> </div> <div class="reply info"> <a class="comment-807155 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807155 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807155"> <li> <div class="comment"> <table class="comment-table" commentId="807161" commentParentId="807155"> <tr> <td class="left"> <div style="position: absolute; left: 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/Enigma20" style="position: relative;"> <img src='https://userpic.codeforces.org/1301418/avatar/3ba73a2cb1eeb8ef.jpg'/> </a> <div><a href="/profile/Enigma20" title="Expert Enigma20" class="rated-user user-blue">Enigma20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807161" href="?#comment-807161" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807155" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807161" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1301418" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807161"> <div class="moveup"> <div class="ttypography"><p>Yes, second case will be optimal. Look at it this way, you have to buy as many products for 50% discount as possible. Now we know $$$i^{th}$$$ product has smaller $$$b_i$$$, so the condition for discount of this product will be fulfilled by taking lesser number of products for 2 rubles. Also it may happen that after taking $$$i^{th}$$$ product for 50% discount, products with higher $$$b_i$$$ can be taken for 50% discount without additional cost of 2 rubles. So, 2nd case will be optimal.</p></div> </div> </div> <div class="reply info"> <a class="comment-807161 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807161 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807161"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807130" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/avdp" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/avdp" title="Newbie avdp" class="rated-user user-gray">avdp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807130" href="?#comment-807130" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807130" class="CommentVoteFrame" data-commentRating="97" data-commentUserId="1840186" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+97</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807130"> <div class="moveup"> <div class="ttypography"><p><img alt=" " src="/predownloaded/0d/c4/0dc4ee86562ac0c8d31bcf482bed113f62f1fda1.jpg" style="max-width: 100.0%;max-height: 100.0%;" /></p><p><a class="rated-user user-red" href="/profile/galen_colin" title="Международный гроссмейстер galen_colin">galen_colin</a> <strong>too</strong></p></div> </div> </div> <div class="reply info"> <a class="comment-807130 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807130 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807130"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807132" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Atomsky" style="position: relative;"> <img src='https://userpic.codeforces.org/336914/avatar/2c5685b756a63503.jpg'/> </a> <div><a href="/profile/Atomsky" title="Newbie Atomsky" class="rated-user user-gray">Atomsky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 05:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807132" href="?#comment-807132" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807132" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="336914" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807132"> <div class="moveup"> <div class="ttypography"><p>I submitted <a href="/contest/1539/submission/120147862" title="Посылка 120147862 от Atomsky">120147862</a> for Problem-C. It gave a wrong result on test 62 in GNU C++17. When I submitted the same code in C++11, it was accepted (<a href="/contest/1539/submission/120149347" title="Посылка 120149347 от Atomsky">120149347</a>).</p><p>It would be helpful if anyone tells me what went wrong in my code.</p></div> </div> </div> <div class="reply info"> <a class="comment-807132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807132"> <li> <div class="comment"> <table class="comment-table" commentId="807136" commentParentId="807132"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/avdp" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/avdp" title="Newbie avdp" class="rated-user user-gray">avdp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 06:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807136" href="?#comment-807136" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807136" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1840186" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807136"> <div class="moveup"> <div class="ttypography"><p>Hey there, It is because of precision error differences in C++11 and C++17, So it is always advised to use <strong>long double</strong> instead of <strong>double</strong>. You will get AC in both versions with <strong>long double</strong>.</p></div> </div> </div> <div class="reply info"> <a class="comment-807136 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807136 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807136"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807165" commentParentId="807132"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/maskman_lucifer" style="position: relative;"> <img src='https://userpic.codeforces.org/1453975/avatar/e7e8769e223b3ab9.jpg'/> </a> <div><a href="/profile/maskman_lucifer" title="Pupil maskman_lucifer" class="rated-user user-green">maskman_lucifer</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807165" href="?#comment-807165" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807165" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1453975" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807165"> <div class="moveup"> <div class="ttypography"><p>In these cases use this (val + d-1 )/ d instead of some ceil on double (Try to avoid doubles if you can do the same with int (precision issue)).<br /> In your case foo[i] = (jar[i] — jar[i-1] + x-1)/x will be good to go.</p></div> </div> </div> <div class="reply info"> <a class="comment-807165 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807165 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807165"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807144" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/UpMing" style="position: relative;"> <img src='https://userpic.codeforces.org/1424136/avatar/2e9bc60a07619853.jpg'/> </a> <div><a href="/profile/UpMing" title="Candidate Master UpMing" class="rated-user user-violet">UpMing</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 06:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807144" href="?#comment-807144" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807144" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="1424136" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807144"> <div class="moveup"> <div class="ttypography"><p>The difficulty range is very large,</p><p>For example, D through E</p></div> </div> </div> <div class="reply info"> <a class="comment-807144 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807144 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807144"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807157" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hurt_FOR_heart" style="position: relative;"> <img src='https://userpic.codeforces.org/1445761/avatar/4bd86d3c8cfb747a.jpg'/> </a> <div><a href="/profile/hurt_FOR_heart" title="Candidate Master hurt_FOR_heart" class="rated-user user-violet">hurt_FOR_heart</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807157" href="?#comment-807157" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807157" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="1445761" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807157"> <div class="moveup"> <div class="ttypography"><p>In problem E, i thing that it's hard to come up with such dp state. Does anyone have a more natural idea for this problem ? </p></div> </div> </div> <div class="reply info"> <a class="comment-807157 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807157 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807157"> <li> <div class="comment"> <table class="comment-table" commentId="807183" commentParentId="807157"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/andr14142" style="position: relative;"> <img src='https://userpic.codeforces.org/620444/avatar/368d81a28bf4f89b.jpg'/> </a> <div><a href="/profile/andr14142" title="Pupil andr14142" class="rated-user user-green">andr14142</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 08:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807183" href="?#comment-807183" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807157" style="font-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="807183" revisionCount="7" revision="7"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">7</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="807183" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="620444" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807183"> <div class="moveup"> <div class="ttypography"><p>A more natural idea is to calculate limits for both hands from the end.<br /> Last move has no limits. The range for both hands of last move is from 0 to m inclusive.<br /> For the previous move check cases. Initially limits impossible m &lt; k &lt; 0.<br /> If you can take the card into left hand, then check, could you keep your right hand for the next move? If left card may be kept, limits for the right hand are the current limits for right hand. Otherwise right hand must be kept for the next move, so intersect current limits for right hand with limits for next move.<br /> The same for the right hand.<br /> Finally we check limits for initial situation, is pair (0,0) allowed.</p></div> </div> </div> <div class="reply info"> <a class="comment-807183 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807183 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807183"> <li> <div class="comment"> <table class="comment-table" commentId="807186" commentParentId="807183"> <tr> <td class="left"> <div style="position: absolute; left: 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/rag-hav" style="position: relative;"> <img src='https://userpic.codeforces.org/1809311/avatar/8456dc0c30997ac5.jpg'/> </a> <div><a href="/profile/rag-hav" title="Expert rag-hav" class="rated-user user-blue">rag-hav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807186" href="?#comment-807186" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807183" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807186" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1809311" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807186"> <div class="moveup"> <div class="ttypography"><p>Isn't that exponential complexity? (two choices in every move)</p></div> </div> </div> <div class="reply info"> <a class="comment-807186 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807186 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807186"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807171" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/deletha" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/deletha" title="Pupil deletha" class="rated-user user-green">deletha</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 07:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807171" href="?#comment-807171" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807171" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1806788" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807171"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1539/submission/120173484" title="Посылка 120173484 от deletha">120173484</a> I am getting runtime error on test 23 in problem C. Unable to understand if it is due to seg fault or overflows. Can someone pls explain</p></div> </div> </div> <div class="reply info"> <a class="comment-807171 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807171 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807171"> <li> <div class="comment"> <table class="comment-table" commentId="807178" commentParentId="807171"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HowSoOrz" style="position: relative;"> <img src='https://userpic.codeforces.org/1519509/avatar/24d272c5a2a620a1.jpg'/> </a> <div><a href="/profile/HowSoOrz" title="Specialist HowSoOrz" class="rated-user user-cyan">HowSoOrz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 08:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807178" href="?#comment-807178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807171" style="font-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="807178" 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="807178" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1519509" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807178"> <div class="moveup"> <div class="ttypography"><p>Just return when the valid array size is 0. You cant use binary search when the size of the valid vector is 0. Reason: v.begin()=points to first element, v.end() points to next element of last ele.</p><p><a href="/contest/1539/submission/120176292" title="Посылка 120176292 от HowSoOrz">120176292</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807178"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807185" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noobKunal" style="position: relative;"> <img src='https://userpic.codeforces.org/1183443/avatar/73aa8f3ddfbcab8a.jpg'/> </a> <div><a href="/profile/noobKunal" title="Expert noobKunal" class="rated-user user-blue">noobKunal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807185" href="?#comment-807185" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807185" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1183443" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807185"> <div class="moveup"> <div class="ttypography"><p>Can anyone check <a href="https://codeforces.com/contest/1539/submission/120132934">my submission</a> for D. Its giving TLE at tc 11 and it seems that its because of initial sorting itself (and not even entering while loop).</p></div> </div> </div> <div class="reply info"> <a class="comment-807185 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807185 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807185"> <li> <div class="comment"> <table class="comment-table" commentId="807194" commentParentId="807185"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/i_aM_SnEhaal" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/i_aM_SnEhaal" title="Pupil i_aM_SnEhaal" class="rated-user user-green">i_aM_SnEhaal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807194" href="?#comment-807194" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807185" style="font-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="807194" 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="807194" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1279863" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807194"> <div class="moveup"> <div class="ttypography"><p>I tried to submit your solution with just by changing the compare function in sort and it worked. <a href="https://codeforces.com/contest/1539/submission/120179243">Here is the submission have a look</a> just compare it with your solution to see the changes I made.The problem was in how you are defining the compare function in sort. What I have understood is &lt;= or &gt;= is slower than &lt; or &gt; which is causing the problem. For more details please go through <a href="https://codeforces.com/blog/entry/70237">this blog</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-807194 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807194 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807194"> <li> <div class="comment"> <table class="comment-table" commentId="807201" commentParentId="807194"> <tr> <td class="left"> <div style="position: absolute; left: 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/noobKunal" style="position: relative;"> <img src='https://userpic.codeforces.org/1183443/avatar/73aa8f3ddfbcab8a.jpg'/> </a> <div><a href="/profile/noobKunal" title="Expert noobKunal" class="rated-user user-blue">noobKunal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807201" href="?#comment-807201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807194" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807201" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1183443" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807201"> <div class="moveup"> <div class="ttypography"><p>Thanks it passed. Wish i've known this before</p></div> </div> </div> <div class="reply info"> <a class="comment-807201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807201"> <li> <div class="comment"> <table class="comment-table" commentId="807205" commentParentId="807201"> <tr> <td class="left"> <div style="position: absolute; left: 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/i_aM_SnEhaal" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/i_aM_SnEhaal" title="Pupil i_aM_SnEhaal" class="rated-user user-green">i_aM_SnEhaal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807205" href="?#comment-807205" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807205" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1279863" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807205"> <div class="moveup"> <div class="ttypography"><p>I also learnt it the hard way. After getting TLE on TC 11 twice during the contest and then submitting the same code in 8 different ways after the contest was able to figure it out. </p></div> </div> </div> <div class="reply info"> <a class="comment-807205 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807205 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807205"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="1035068" commentParentId="807194"> <tr> <td class="left"> <div style="position: absolute; left: 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/BDboy" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/BDboy" title="Expert BDboy" class="rated-user user-blue">BDboy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/05/2023 21:16">4 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1035068" href="?#comment-1035068" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807194" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1035068" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2468471" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-1035068"> <div class="moveup"> <div class="ttypography"><p>Thanks, I wont be learning this the hard way. :)</p></div> </div> </div> <div class="reply info"> <a class="comment-1035068 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1035068 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1035068"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807188" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vkgainz" style="position: relative;"> <img src='https://userpic.codeforces.org/679880/avatar/f966b85a769e4f5.jpg'/> </a> <div><a href="/profile/vkgainz" title="Grandmaster vkgainz" class="rated-user user-red">vkgainz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 09:12">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807188" href="?#comment-807188" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807188" class="CommentVoteFrame" data-commentRating="51" data-commentUserId="679880" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+51</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807188"> <div class="moveup"> <div class="ttypography"><p>I found D to be a lot easier to think about using binary search (which solves in $$$O(n\log(10^{14}))$$$. Similar to the editorial, sort with respect to $$$b_i$$$. Now, let $$$x$$$ be the number of items with price $$$1$$$ and $$$y$$$ be the number of items with price $$$2$$$. Then, our answer is equal to $$$x + 2 \cdot y = y + \sum_{i = 1} ^ {n} a_i$$$, so it suffices to minimize $$$y$$$.</p><p>Let's binary search on this. Suppose we set $$$y = k$$$. How do we know if this is enough? First we make two simple observations:</p> <ul> <li><p>We buy all $$$k$$$ items at the very beginning.</p></li> <li><p>We buy all $$$k$$$ items from a suffix of the sorted array.</p></li> </ul><p>Why does this work? Well, if you are going to buy $$$k$$$ items of price $$$2$$$, you should do it earlier than later, because then we might have more $$$b_i$$$ opened up that gives us items of price $$$1$$$. Similarly, we should be buying our items from a suffix because that way we can maximize the number of items of price $$$1$$$ we get (and, subsequently, minimize the number of items of price $$$2$$$). </p><p>From here it's simple to solve with binary search. To test $$$y = k$$$, start a counter for the number of items bought and an index at $$$0$$$. While the counter is greater than $$$b_{\text{index}}$$$, add $$$a_{\text{index}}$$$ to the counter (since we're getting all of those for price $$$1$$$) and increment the counter. If $$$k$$$ is enough, then the counter should be $$$\geq$$$ the number of items we have in total.</p><p>This explanation may seem a bit complicated, but the ideas involved are simple to arrive at and the implementation is very clean: <a href="https://codeforces.com/contest/1539/submission/120179122">my submission here</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-807188 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807188 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807188"> <li> <div class="comment"> <table class="comment-table" commentId="807238" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ace-in-the-hole" style="position: relative;"> <img src='https://userpic.codeforces.org/725810/avatar/31d6d37857b526e4.jpg'/> </a> <div><a href="/profile/ace-in-the-hole" title="Candidate Master ace-in-the-hole" class="rated-user user-violet">ace-in-the-hole</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 12:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807238" href="?#comment-807238" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807238" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="725810" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807238"> <div class="moveup"> <div class="ttypography"><p>This idea is nice, but it's still not too different from the solution, because we still have to make the observation: buying items with higher b_i is better. I can say, your idea is <strong>not fundamentally different</strong> from the solution's idea. Maybe because this is not a hard problem so we can't see the diversity of the solutions like some others.</p><p>But it sure is a great idea, the thoughts &quot;I should minimize the number of bought items with price 2&quot;, &quot;I can binary search the answer on this&quot;, ... and more, as you explained, are completely natural and can be thought of. Thank you for your contribution!</p></div> </div> </div> <div class="reply info"> <a class="comment-807238 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807238 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807238"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807334" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/faraz16iqbal" style="position: relative;"> <img src='https://userpic.codeforces.org/1534426/avatar/6269999f6a6fd0c7.jpg'/> </a> <div><a href="/profile/faraz16iqbal" title="Expert faraz16iqbal" class="rated-user user-blue">faraz16iqbal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 17:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807334" href="?#comment-807334" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807334" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1534426" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807334"> <div class="moveup"> <div class="ttypography"><p>Thank you, brilliant explanation</p></div> </div> </div> <div class="reply info"> <a class="comment-807334 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807334 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807334"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807893" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DeerInForestovo" style="position: relative;"> <img src='https://userpic.codeforces.org/805889/avatar/8210f0230414d9cc.jpg'/> </a> <div><a href="/profile/DeerInForestovo" title="Master DeerInForestovo" class="rated-user user-orange">DeerInForestovo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 12:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807893" href="?#comment-807893" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807893" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="805889" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807893"> <div class="moveup"> <div class="ttypography"><p>Thanks. In your solution, we finally found a proper position where the things before it were 1 and later than it were 2. So, why not check every possible position and keep some useful information? See <a href="https://codeforces.com/contest/1539/submission/120329507">my submission</a>, which is theoretically O(N) if we use radix sort instead of qsort.</p><p>Sorry for my bad English : )</p></div> </div> </div> <div class="reply info"> <a class="comment-807893 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807893 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807893"> <li> <div class="comment"> <table class="comment-table" commentId="807895" commentParentId="807893"> <tr> <td class="left"> <div style="position: absolute; left: 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/DeerInForestovo" style="position: relative;"> <img src='https://userpic.codeforces.org/805889/avatar/8210f0230414d9cc.jpg'/> </a> <div><a href="/profile/DeerInForestovo" title="Master DeerInForestovo" class="rated-user user-orange">DeerInForestovo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/23/2021 12:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807895" href="?#comment-807895" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807893" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807895" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="805889" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807895"> <div class="moveup"> <div class="ttypography"><p>In my submission, 'Hab' meant 'Had bought'</p></div> </div> </div> <div class="reply info"> <a class="comment-807895 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807895 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807895"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="868233" commentParentId="807188"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/yeetholmes619" style="position: relative;"> <img src='https://userpic.codeforces.org/1957631/avatar/1ad3067143e8096e.jpg'/> </a> <div><a href="/profile/yeetholmes619" title="Expert yeetholmes619" class="rated-user user-blue">yeetholmes619</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/17/2021 01:45">22 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-868233" href="?#comment-868233" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807188" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="868233" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1957631" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-868233"> <div class="moveup"> <div class="ttypography"><p>I'm sorry for replying to your comment that is 6 months old, but reading this cleared all my doubts and troubles with this problem, I struggled with finding the right train of thought to solve this problem and the way you explained it removed all of my confusion regarding this.</p><p>The two pointer technique althought gives AC, didn't make the underlying idea behind the solution, i.e x+2y will be our minimum cost which can be re-written as ∑ai + y obvious to me, which your approach clearly does. Thanks a lot! your comment not only helped me in this problem but will help me in future problems as well as it gave light to the right mindset while solving the problem :)</p></div> </div> </div> <div class="reply info"> <a class="comment-868233 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-868233 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-868233"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807217" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Delver0227" style="position: relative;"> <img src='https://userpic.codeforces.org/1594171/avatar/5f6e96d412ba3fde.jpg'/> </a> <div><a href="/profile/Delver0227" title="Specialist Delver0227" class="rated-user user-cyan">Delver0227</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 10:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807217" href="?#comment-807217" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807217" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1594171" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807217"> <div class="moveup"> <div class="ttypography"><p>I have a different way of implementing problem D that is more concise. Considering buying items backwards, we want to the last item we buy is the item with the highest discount requirement(which can be achieved). Which means all we need to do is suppose we have already bought all the items and the number of items is $$$num$$$. Sorting $$$b_i$$$ in non-decreasing order, skip the items that are impossible to get a discount on and take $$$num_i = \min(num-b_i,a_i)$$$ as the number of $$$item_i$$$ which we can buy with a discount. Remember to substract $$$num_i$$$ from $$$num$$$. After iterating $$$i$$$ through all the items, the sum of $$$num_i$$$ is the total number of item that we can get a discount on.</p><p>The code goes like this:<a href="https://paste.ubuntu.com/p/8mwW8n2yfQ/">https://paste.ubuntu.com/p/8mwW8n2yfQ/</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807217 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807217 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807217"> <li> <div class="comment"> <table class="comment-table" commentId="809490" commentParentId="807217"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Whimpers" style="position: relative;"> <img src='https://userpic.codeforces.org/1507315/avatar/b11dc9bbdf35d8d9.jpg'/> </a> <div><a href="/profile/Whimpers" title="Expert Whimpers" class="rated-user user-blue">Whimpers</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 03:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809490" href="?#comment-809490" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807217" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809490" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1507315" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809490"> <div class="moveup"> <div class="ttypography"><p>why does this work? dont 1's also count towards the total items bought. from what i can see from your solution it is just comparing if the number of items left is greater than the b of the current last item, but if there is an item that has a lot more a than it has b, wouldnt it also be useful in increasing the total number bought and thus would have to be used in the total number of items bought?</p></div> </div> </div> <div class="reply info"> <a class="comment-809490 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809490 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809490"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807229" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Samrev" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Samrev" title="Expert Samrev" class="rated-user user-blue">Samrev</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 11:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807229" href="?#comment-807229" style="font-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="807229" 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="807229" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-19" data-commentUserId="1932888" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807229"> <div class="moveup"> <div class="ttypography"><p>Test:</p> <pre><code>5 3 10 2 12 1 11 3 10 1 8 </code></pre><p>Submission: <a href="/contest/1539/submission/120129309" title="Посылка 120129309 от Kakashi_099">120129309</a></p><p>Output : 20 Correct Output: 19</p><p>This submission is getting accepted but however the above test case shows wrong output. Correct Output should be 19, instead of 20.</p><p><a class="rated-user user-red" href="/profile/talant" title="Гроссмейстер talant">talant</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807229 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807229 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807229"> <li> <div class="comment"> <table class="comment-table" commentId="807256" commentParentId="807229"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/talant" style="position: relative;"> <img src='https://userpic.codeforces.org/1215930/avatar/cc80e217f41ccfb0.jpg'/> </a> <div><a href="/profile/talant" title="Grandmaster talant" class="rated-user user-red">talant</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807256" href="?#comment-807256" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807229" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807256" class="CommentVoteFrame" data-commentRating="58" data-commentUserId="1215930" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+58</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807256"> <div class="moveup"> <div class="ttypography"><p>Stop tagging me, this task isn't even mine</p></div> </div> </div> <div class="reply info"> <a class="comment-807256 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807256 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807256"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807232" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Anish_Bashyal" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Anish_Bashyal" title="Pupil Anish_Bashyal" class="rated-user user-green">Anish_Bashyal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 12:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807232" href="?#comment-807232" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807232" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1411502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807232"> <div class="moveup"> <div class="ttypography"><p><strong>Problem D</strong></p><p>Proof that buying more items of some product than needed doesn't make the answer better. Let's suppose we have already achieved an product (say product A) which we can buy at discount. Now consider we have to buy next product (say product B). </p><p><strong>N</strong> be the number of product B we have to buy, and <strong>d</strong> be the total purchases required before discount and <strong>c</strong> be the amount of items we have already purchased. Then, </p><p><strong>Case I (buy more of product A and then B)</strong></p><p>Total cost for buying product B = <strong>(d-c)*1 + (N*1)</strong> = <strong>d-c+N</strong></p><p><strong>Case II (only buying product B)</strong></p><p>Total cost for buying product B = <strong>2 * (d-c) + ( N-( d-c ) )</strong> = <strong>d-c+N</strong> </p><p>So both the cases cost the same. But this is a special scenario. If we had different percentage of discount, then the above cases wouldn't be equal. </p><p>If we say <strong>m</strong> as discount percentage and <strong>x</strong> as normal price then, </p><p><strong>Case I</strong></p><p><em>mx(d-c) + Nmx</em></p><p><strong>Case II</strong></p><p><em>x(d-c) + (N-d+c)mx</em></p><p>Equating both cases, we get <strong>m = 0.5 or 50%</strong>..</p><p>So only when the discount percentage is 50%, buying more of a discounted product or buying only the required quantity of each products doesn't matter. Hence also in this case, doesn't matter.</p><p>Sorry for writing just the obvious algebra but wanted to share anyway :)</p></div> </div> </div> <div class="reply info"> <a class="comment-807232 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807232 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807232"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807240" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hurt_FOR_heart" style="position: relative;"> <img src='https://userpic.codeforces.org/1445761/avatar/4bd86d3c8cfb747a.jpg'/> </a> <div><a href="/profile/hurt_FOR_heart" title="Candidate Master hurt_FOR_heart" class="rated-user user-violet">hurt_FOR_heart</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807240" href="?#comment-807240" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807240" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="1445761" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807240"> <div class="moveup"> <div class="ttypography"><p>in E</p> <ul> <li>Card in query i fits constraints on value written on card in left hand in queries with indexes [i,j).</li> </ul><p>i think it's [i,j] isn't it ? Because we have card in i for query j too </p></div> </div> </div> <div class="reply info"> <a class="comment-807240 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807240 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807240"> <li> <div class="comment"> <table class="comment-table" commentId="807271" commentParentId="807240"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TeaTime" style="position: relative;"> <img src='https://userpic.codeforces.org/1199093/avatar/f1cbbd424f7d3cf7.jpg'/> </a> <div><a href="/profile/TeaTime" title="Master TeaTime" class="rated-user user-orange">TeaTime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:25">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807271" href="?#comment-807271" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807240" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807271" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="1199093" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807271"> <div class="moveup"> <div class="ttypography"><p>It's [i, j) because card j was already taken in right hand.</p></div> </div> </div> <div class="reply info"> <a class="comment-807271 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807271 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807271"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807273" commentParentId="807240"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/TeaTime" style="position: relative;"> <img src='https://userpic.codeforces.org/1199093/avatar/f1cbbd424f7d3cf7.jpg'/> </a> <div><a href="/profile/TeaTime" title="Master TeaTime" class="rated-user user-orange">TeaTime</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807273" href="?#comment-807273" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807240" style="font-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="807273" 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="807273" class="CommentVoteFrame" data-commentRating="16" data-commentUserId="1199093" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+16</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807273"> <div class="moveup"> <div class="ttypography"><p>Oh, you are correct, I mistook it with something else. Thanks for noticing!</p><p>Edit: editorial was fixed.</p></div> </div> </div> <div class="reply info"> <a class="comment-807273 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807273 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807273"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807241" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/pucuk16" style="position: relative;"> <img src='https://userpic.codeforces.org/1458650/avatar/a688a695b97d78cb.jpg'/> </a> <div><a href="/profile/pucuk16" title="Newbie pucuk16" class="rated-user user-gray">pucuk16</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807241" href="?#comment-807241" style="font-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="807241" 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="807241" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1458650" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807241"> <div class="moveup"> <div class="ttypography"><p>hai.. where my code gone wrong..? please help me..<br /> for problem C <br /> thx <a href="https://codeforces.com/contest/1539/submission/120116110">code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807241 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807241 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807241"> <li> <div class="comment"> <table class="comment-table" commentId="807335" commentParentId="807241"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bwxnQAQ" style="position: relative;"> <img src='https://userpic.codeforces.org/1816180/avatar/1179db2c2821d194.jpg'/> </a> <div><a href="/profile/bwxnQAQ" title="Expert bwxnQAQ" class="rated-user user-blue">bwxnQAQ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 17:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807335" href="?#comment-807335" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807241" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807335" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="1816180" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807335"> <div class="moveup"> <div class="ttypography"><p>You should check line 37.You change d continuously without initializing.The d on the right side of each formula in line 37 should be the d in line 32 instead of the last calculated d.</p></div> </div> </div> <div class="reply info"> <a class="comment-807335 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807335 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807335"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807251" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/spookywooky" style="position: relative;"> <img src='https://userpic.codeforces.org/872585/avatar/a8efaf71cbe05928.jpg'/><img title='Почетный бейдж за поддержку Codeforces на его 10-летие' src='//codeforces.org/s/81027/images/if_medal-bronze-blue_46108.png' style='position:absolute;bottom:-4px;right:-6px'/> </a> <div><a href="/profile/spookywooky" title="Specialist spookywooky" class="rated-user user-cyan">spookywooky</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807251" href="?#comment-807251" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807251" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="872585" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807251"> <div class="moveup"> <div class="ttypography"><p>Explanation to E sounds like it would be possible to explain it in an understandable way.</p></div> </div> </div> <div class="reply info"> <a class="comment-807251 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807251 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807251"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807258" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 13:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807258" href="?#comment-807258" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807258" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807258"> <div class="moveup"> <div class="ttypography"><p><strong>If there is an item which costs 1, then we will not make the answer worse by buying this item.</strong></p><p>Why is that? For example, consider a situation where we've already bought all items, except for one, and it costs 2, and to make it cost 1 we need to buy 2 more items. In that case it would be cheaper to buy one left item and spend 2 instead of buing two more random items at cost 1 and finally buing one last item, spending 3 in total.</p></div> </div> </div> <div class="reply info"> <a class="comment-807258 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807258 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807258"> <li> <div class="comment"> <table class="comment-table" commentId="807275" commentParentId="807258"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807275" href="?#comment-807275" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807258" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807275" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807275"> <div class="moveup"> <div class="ttypography"><p>In your example you are explicitly making the cost of that item by buying more products of other items. But the statement means that if by buying other items and within limits i.e. less that $$$a_i$$$, then you should buy the items of cost 1.</p></div> </div> </div> <div class="reply info"> <a class="comment-807275 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807275 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807275"> <li> <div class="comment"> <table class="comment-table" commentId="807277" commentParentId="807275"> <tr> <td class="left"> <div style="position: absolute; left: 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/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 14:54">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807277" href="?#comment-807277" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807275" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807277" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807277"> <div class="moveup"> <div class="ttypography"><p>Thanks, that explains it:)</p></div> </div> </div> <div class="reply info"> <a class="comment-807277 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807277 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807277"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807331" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/NoobCpp" style="position: relative;"> <img src='https://userpic.codeforces.org/1716219/avatar/14a123abec8289d0.jpg'/> </a> <div><a href="/profile/NoobCpp" title="Specialist NoobCpp" class="rated-user user-cyan">NoobCpp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 17:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807331" href="?#comment-807331" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807331" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1716219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807331"> <div class="moveup"> <div class="ttypography"><p>Although E and F was more difficult than the rest, the contest was great. First time reach to Expert!!</p><p>Sr about my bad Eng :p</p></div> </div> </div> <div class="reply info"> <a class="comment-807331 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807331 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807331"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807364" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/livlyf_168" style="position: relative;"> <img src='https://userpic.codeforces.org/1919608/avatar/cf064edf00e3eea6.jpg'/> </a> <div><a href="/profile/livlyf_168" title="Pupil livlyf_168" class="rated-user user-green">livlyf_168</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807364" href="?#comment-807364" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807364" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1919608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807364"> <div class="moveup"> <div class="ttypography"><p>Hey, can anyone help me with problem C. Don't know why is it giving WA on test 10. Below is my submission — <a href="/contest/1539/submission/120223010" title="Посылка 120223010 от livlyf_168">120223010</a>. I have used the same approach, except that I have taken The number of elements required to fill the gap as floor((d-1)/x). </p></div> </div> </div> <div class="reply info"> <a class="comment-807364 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807364 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807364"> <li> <div class="comment"> <table class="comment-table" commentId="807370" commentParentId="807364"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/itish" style="position: relative;"> <img src='https://userpic.codeforces.org/1589684/avatar/d4fea913edfbab4b.jpg'/> </a> <div><a href="/profile/itish" title="Candidate Master itish" class="rated-user user-violet">itish</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807370" href="?#comment-807370" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807364" style="font-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="807370" 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="807370" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1589684" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807370"> <div class="moveup"> <div class="ttypography"><p>Change vector(int)split to vector(llint) split and it gets accepted</p></div> </div> </div> <div class="reply info"> <a class="comment-807370 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807370 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807370"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807374" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Hotas" style="position: relative;"> <img src='https://userpic.codeforces.org/1150129/avatar/590cdb757ae4763a.jpg'/> </a> <div><a href="/profile/Hotas" title="Newbie Hotas" class="rated-user user-gray">Hotas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807374" href="?#comment-807374" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807374" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1150129" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807374"> <div class="moveup"> <div class="ttypography"><p>Can anyone tell me where am I doing wrong? I am getting wrong answer on test case 10. Problem C. Submission : <a href="/contest/1539/submission/120227942" title="Посылка 120227942 от Hotas">120227942</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807374 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807374 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807374"> <li> <div class="comment"> <table class="comment-table" commentId="807397" commentParentId="807374"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 20:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807397" href="?#comment-807397" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807374" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807397" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807397"> <div class="moveup"> <div class="ttypography"><p>I think the problem is that you have int[] a instead of ll[] a. Each element can be up to 1e18.</p></div> </div> </div> <div class="reply info"> <a class="comment-807397 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807397 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807397"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807378" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/coderaman327" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/coderaman327" title="Expert coderaman327" class="rated-user user-blue">coderaman327</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 19:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807378" href="?#comment-807378" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807378" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="886853" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807378"> <div class="moveup"> <div class="ttypography"><p>Can someone please tell me what my mistake is in problem D? <a href="https://codeforces.com/contest/1539/submission/120100696">My submission</a> Thanks in advance!!</p></div> </div> </div> <div class="reply info"> <a class="comment-807378 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807378 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807378"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807400" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/abyboi" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/abyboi" title="Pupil abyboi" class="rated-user user-green">abyboi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/21/2021 21:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807400" href="?#comment-807400" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807400" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1833158" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807400"> <div class="moveup"> <div class="ttypography"><p>Can someone help me with Problem D? My submission is</p><p><a href="https://codeforces.com/contest/1539/submission/120232784">https://codeforces.com/contest/1539/submission/120232784</a></p><p>Thanks in advance!</p></div> </div> </div> <div class="reply info"> <a class="comment-807400 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807400 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807400"> <li> <div class="comment"> <table class="comment-table" commentId="807478" commentParentId="807400"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/andr14142" style="position: relative;"> <img src='https://userpic.codeforces.org/620444/avatar/368d81a28bf4f89b.jpg'/> </a> <div><a href="/profile/andr14142" title="Pupil andr14142" class="rated-user user-green">andr14142</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 09:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807478" href="?#comment-807478" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807400" style="font-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="807478" 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="807478" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="620444" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807478"> <div class="moveup"> <div class="ttypography"><p>Your solution has not correct comparison in the case of whole buying goods without discount:<br /> else if (total_bought + products[j].F &lt; products[i].S)<br /> Correct comparison is:<br /> else if (total_bought + products[j].F &lt;= products[i].S)</p></div> </div> </div> <div class="reply info"> <a class="comment-807478 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807478 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807478"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807520" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Madara_Uzumaki" style="position: relative;"> <img src='https://userpic.codeforces.org/1621901/avatar/28eb09a48344e5fb.jpg'/> </a> <div><a href="/profile/Madara_Uzumaki" title="Newbie Madara_Uzumaki" class="rated-user user-gray">Madara_Uzumaki</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 11:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807520" href="?#comment-807520" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807520" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1621901" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807520"> <div class="moveup"> <div class="ttypography"><p>In <strong>problem</strong> C i ran the code in <strong>PyPy3</strong> the code got <strong>TLE in test case 18</strong> but when I ran the same code in <strong>Python3</strong> the code got <strong>accepted</strong> Can anyone clarify why did that happen?</p></div> </div> </div> <div class="reply info"> <a class="comment-807520 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807520 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807520"> <li> <div class="comment"> <table class="comment-table" commentId="807527" commentParentId="807520"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/casul" style="position: relative;"> <img src='https://userpic.codeforces.org/1690955/avatar/21ae0e21fe431dd7.jpg'/> </a> <div><a href="/profile/casul" title="Specialist casul" class="rated-user user-cyan">casul</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 12:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807527" href="?#comment-807527" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807520" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807527" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1690955" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807527"> <div class="moveup"> <div class="ttypography"><p>You may wanna check out this blog:</p><p><a href="https://codeforces.com/blog/entry/82989">https://codeforces.com/blog/entry/82989</a></p></div> </div> </div> <div class="reply info"> <a class="comment-807527 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807527 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807527"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="807629" commentParentId="807520"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aberent" 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/aberent" title="Specialist aberent" class="rated-user user-cyan">aberent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 18:13">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807629" href="?#comment-807629" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807520" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807629" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1157884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807629"> <div class="moveup"> <div class="ttypography"><p>I too got some strange behaviour with PyPy3 with test 18. Every version I tried printed a result and then (after it should have finished), got TLE. I wonder whether there is a bug somewhere here. See <a href="https://codeforces.com/blog/entry/92011">my blog entry</a>.</p></div> </div> </div> <div class="reply info"> <a class="comment-807629 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807629 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807629"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807566" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zvsevolod" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/zvsevolod" title="Newbie zvsevolod" class="rated-user user-gray">zvsevolod</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 14:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807566" href="?#comment-807566" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807566" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1271216" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-807566"> <div class="moveup"> <div class="ttypography"><p>In problem C Java solution with Long[] array gets accepted, but long[] array solution gets TLE. (16th line in both solutions) </p><p>ACC: <a href="https://codeforces.com/contest/1539/submission/120284760">https://codeforces.com/contest/1539/submission/120284760</a> <br /> TLE: <a href="https://codeforces.com/contest/1539/submission/120284797">https://codeforces.com/contest/1539/submission/120284797</a></p><p>Could someone explain me why reference type works faster than primitive in this example?</p></div> </div> </div> <div class="reply info"> <a class="comment-807566 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807566 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807566"> <li> <div class="comment"> <table class="comment-table" commentId="807620" commentParentId="807566"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/aberent" 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/aberent" title="Specialist aberent" class="rated-user user-cyan">aberent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 18:06">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807620" href="?#comment-807620" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807566" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="807620" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1157884" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-807620"> <div class="moveup"> <div class="ttypography"><p>Apparently Java uses different sorting algorithms for integers (including longs) and objects. The algorithm for integers is generally faster, but its worst case is worse. You might have simply been unlucky. See the implementation notes for the two versions of sort: <a href="https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(long%5B%5D">https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(long%5B%5D</a>) <a href="https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(java.lang.Object%5B%5D">https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(java.lang.Object%5B%5D</a>)</p></div> </div> </div> <div class="reply info"> <a class="comment-807620 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807620 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807620"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="807726" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/quinoa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/quinoa" title="Expert quinoa" class="rated-user user-blue">quinoa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/22/2021 23:40">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-807726" href="?#comment-807726" style="font-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="807726" 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="807726" class="CommentVoteFrame" data-commentRating="7" data-commentUserId="592293" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;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-807726"> <div class="moveup"> <div class="ttypography"><p>I had a hard time understanding the tutorial for problem E. This is my attempt at making it easier to understand.</p><p><strong>Easier problem: jump game</strong></p><p>Consider <a href="https://leetcode.com/problems/jump-game/">this</a> easier problem: you have an array $$$x$$$ where $$$x[i]$$$ means what the farthest is that you can jump from position $$$i$$$. Is it possible to reach the last element in the array if you start from position 0?</p><p>We can solve it with a DP where $$$dp[i]$$$ = can we reach the end if we start from position i? The solution to the problem is then equal to $$$dp[0]$$$. The transitions are like this: $$$dp[i]$$$ = $$$dp[i + 1]$$$ $$$||$$$ $$$dp[i + 2]$$$ $$$||$$$ ... $$$||$$$ $$$dp[i + x[i]]$$$. There are $$$N$$$ states and the transitions are $$$O(N)$$$ so this runs in $$$O(N^2)$$$.</p><p>We can make every transition $$$O(1)$$$ with a greedy insight. Instead of checking $$$dp[i + 1]$$$, ..., $$$dp[i + x[i]]$$$ we only need to check $$$dp[j]$$$ where $$$j$$$ is the leftmost position from which we can reach the end. The reason this works is that the leftmost position from which we can reach the end has the best probability of being within our jumping range. We can keep track of this leftmost position as we compute each state in a bottom up fashion.</p> <pre><code>int leftmost_possible = N - 1; for (int i = N - 2; i &gt;= 0; --i) { if (leftmost_possible &lt;= i + x[i]) { dp[i] = true; leftmost_possible = i; } } </code></pre><p><strong>Back to problem E</strong></p><p>We can again solve this with an $$$O(N^2)$$$ DP where $$$dp(x, y)$$$ = can we finish if card with index $$$x$$$ is in the left hand, and card with index $$$y$$$ is in the right hand (and we have just answered query $$$max(x, y)$$$). </p><p>We can notice that we can reduce the number of states to $$$N$$$. Because if we are at $$$dp(x, y)$$$ (WLOG $$$x &gt; y$$$) then</p> <ul> <li>either we will keep replacing the card in the left hand until we reach the end</li> <li>or at some point we have to take something in the right hand and we transition to state $$$dp(k, k + 1)$$$</li> </ul><p>So if we are at state (x, y) then in the next step either we are done, or we will transition to $$$dp(k, k + 1)$$$. Therefore (since we start at state $$$dp(0, 1)$$$) we will only visit states of the type $$$dp(k, k + 1)$$$ (and $$$dp(k - 1, k)$$$), and there are only $$$O(N)$$$ of those.</p><p>The transition is now $$$O(N)$$$ because we have to consider every $$$k$$$ such that $$$dp(k, k + 1)$$$ works. But with the same greedy insight as in the jump game problem we can reduce that to $$$O(1)$$$. Again we can store &quot;the leftmost k that works&quot; as we compute the states and therefore we can find the transition in $$$O(1)$$$.</p><p>Now of course in this problem another hard part is to compute the &quot;maximum jump length&quot; at every position. In the jump game problem this was given in the input, whereas here we have to compute it. For sure you can do it in logarithmic time with a segment tree (I saw it in <a href="https://www.youtube.com/watch?v=seaskdKf2sI">Colin Galen's video</a>). But apparently you can also do it in $$$O(1)$$$ since the solution runs in O(N) according to the tutorial. I didn't think about optimizing that part yet.</p></div> </div> </div> <div class="reply info"> <a class="comment-807726 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-807726 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-807726"> <li> <div class="comment"> <table class="comment-table" commentId="852194" commentParentId="807726"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ahshafi" style="position: relative;"> <img src='https://userpic.codeforces.org/818506/avatar/d65d006cfdce087a.jpg'/> </a> <div><a href="/profile/ahshafi" title="Candidate Master ahshafi" class="rated-user user-violet">ahshafi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Oct/19/2021 17:24">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-852194" href="?#comment-852194" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-807726" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="852194" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="818506" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-852194"> <div class="moveup"> <div class="ttypography"><p>me too confused about how to compute maximum jump length in O(1) </p></div> </div> </div> <div class="reply info"> <a class="comment-852194 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-852194 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-852194"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808157" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sg55" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sg55" title="Newbie sg55" class="rated-user user-gray">sg55</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/24/2021 05:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808157" href="?#comment-808157" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808157" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1445980" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808157"> <div class="moveup"> <div class="ttypography"><p>I have used 2 the same method as used by most of the other coders but my code is giving tle. Can please someone look and tell me why it is? <a href="/contest/1539/submission/120407076" title="Посылка 120407076 от sg55">120407076</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808157 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808157 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808157"> <li> <div class="comment"> <table class="comment-table" commentId="808253" commentParentId="808157"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zvsevolod" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/zvsevolod" title="Newbie zvsevolod" class="rated-user user-gray">zvsevolod</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/24/2021 13:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808253" href="?#comment-808253" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808157" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808253" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="1271216" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808253"> <div class="moveup"> <div class="ttypography"><p>Try to use Long[] array instead of long[]. Also you may read my comment above.</p></div> </div> </div> <div class="reply info"> <a class="comment-808253 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808253 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808253"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hritik27" style="position: relative;"> <img src='https://userpic.codeforces.org/1232410/avatar/af014e1c10ef2a19.jpg'/> </a> <div><a href="/profile/hritik27" title="Newbie hritik27" class="rated-user user-gray">hritik27</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/24/2021 19:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808320" href="?#comment-808320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808320" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1232410" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808320"> <div class="moveup"> <div class="ttypography"><p>Can someone please help me with problem A?? Can't understand the solution give.</p></div> </div> </div> <div class="reply info"> <a class="comment-808320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808320"> <li> <div class="comment"> <table class="comment-table" commentId="810306" commentParentId="808320"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/songzy12" style="position: relative;"> <img src='https://userpic.codeforces.org/249570/avatar/3c83a5ef255ff4d6.jpg'/> </a> <div><a href="/profile/songzy12" title="Pupil songzy12" class="rated-user user-green">songzy12</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/30/2021 17:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810306" href="?#comment-810306" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808320" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810306" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="249570" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810306"> <div class="moveup"> <div class="ttypography"><p>1. First consider the case where there are infinite participants. Then each participant would be disturbed by $$$t/x$$$ participants following him. </p><p>2. Then consider the case that $$$n$$$ is finite but large enough, then the first participant would be disturbed by $$$t/x$$$, the same for participant 2, ..., until $$$k$$$. </p><p>For the participants beyond k, the number of participants that would disturb them are decreased by 1 each time, i.e., $$$t/x - 1$$$, $$$t/x - 2$$$, until 0 for the last participant.</p><p>There are $$$t/x$$$ numbers from $$$t/x - 1$$$ until 0, thus we know $$$k = n - t/x$$$.</p><p>So the answer would be $$$(n-t/x) * (t/x) + (t/x-1)*(t/x)/2$$$.</p><p>3. The $$$min$$$ and $$$max$$$ in the answer is to solve the case where n is not large enough, i.e., when $$$n &lt; t/x$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-810306 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810306 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810306"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808360" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/augurar" style="position: relative;"> <img src='https://userpic.codeforces.org/391071/avatar/8a814e47f9aacb44.jpg'/> </a> <div><a href="/profile/augurar" title="Expert augurar" class="rated-user user-blue">augurar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 02:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808360" href="?#comment-808360" style="font-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="808360" 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="808360" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="391071" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808360"> <div class="moveup"> <div class="ttypography"><p>I'm glad I didn't participate in this one officially. Problem C was easy but I kept getting a TLE for stupid language-specific reasons:</p> <ul> <li><p>My <a href="https://codeforces.com/contest/1539/submission/120478273">Python solution</a> got TLE on test 18 with PyPy3, but the same code passed with Python 3.</p></li> <li><p>My <a href="https://codeforces.com/contest/1539/submission/120478521">Java solution</a> got TLE on test 61, but passed if I changed <code>long[]</code> to <code>Long[]</code>. (This is kind of my fault for not knowing Java uses a worst-case O(n^2) sort for primitive arrays.)</p></li> <li><p>My <a href="https://codeforces.com/contest/1539/submission/120480356">C++ solution</a> passed with no special optimization.</p></li> </ul><p>In my opinion that's an indication that the time limit is overly strict, especially for an ABC problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-808360 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808360 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808360"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="816645" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/comseung18_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/comseung18_" title="Expert comseung18_" class="rated-user user-blue">comseung18_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/15/2021 09:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-816645" href="?#comment-816645" style="font-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="816645" 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="816645" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275870" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-816645"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1539/submission/122552751" title="Посылка 122552751 от comseung18_">122552751</a> why my solution A is not correct ? ans1 is Editorial solution ans2 is my solution</p><p>I checked my ans2 in many times. but ans1 equals ans2..<br />~~~~~ import random k = int(input()) for _ in range(k): n = random.randint(1,2*1000000000) x = random.randint(1,2*1000000000) t = random.randint(1,2*1000000000) tmp = t//x ans1 = max(0,n-tmp)*tmp + min(n-1,tmp-1)*min(n,tmp)//2 ans2 = tmp*n — tmp*tmp + tmp*n — ((2*n-tmp+1)*tmp)//2 if ans1 != ans2: print(ans1,ans2) ~~~~~</p></div> </div> </div> <div class="reply info"> <a class="comment-816645 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-816645 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-816645"> <li> <div class="comment"> <table class="comment-table" commentId="816647" commentParentId="816645"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/comseung18_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/comseung18_" title="Expert comseung18_" class="rated-user user-blue">comseung18_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/15/2021 09:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-816647" href="?#comment-816647" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-816645" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="816647" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1275870" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-816647"> <div class="moveup"> <div class="ttypography"><p>when , t/x &gt; n , ans2 is wrong sorry</p></div> </div> </div> <div class="reply info"> <a class="comment-816647 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-816647 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-816647"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="984743" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PrickyToTheMoon" style="position: relative;"> <img src='https://userpic.codeforces.org/1432360/avatar/422cb9d88c769b8d.jpg'/> </a> <div><a href="/profile/PrickyToTheMoon" title="Pupil PrickyToTheMoon" class="rated-user user-green">PrickyToTheMoon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Dec/24/2022 21:10">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-984743" href="?#comment-984743" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="984743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1432360" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-984743"> <div class="moveup"> <div class="ttypography"><p><a href="/contest/1539/submission/186604051" title="Submission 186604051 by PrickyToTheMoon">186604051</a></p><p>Please help. Cannot understand why getting WA on test case 18. My approach matches perfectly with editorial.</p><p>Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-984743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-984743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-984743"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="995447" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Mohsina_Shaikh" style="position: relative;"> <img src='https://userpic.codeforces.org/1396580/avatar/6f21616a2d8d578.jpg'/> </a> <div><a href="/profile/Mohsina_Shaikh" title="Newbie Mohsina_Shaikh" class="rated-user user-gray">Mohsina_Shaikh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/25/2023 07:37">8 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-995447" href="?#comment-995447" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="995447" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1396580" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-995447"> <div class="moveup"> <div class="ttypography"><p>can anyone please explain how problem B can be solved using DP.</p></div> </div> </div> <div class="reply info"> <a class="comment-995447 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-995447 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-995447"> </ul> </div> <br/> <div id="editBox-100475" 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 firstPreview100475 = true; var lastPreviewContent100475 = ''; 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=100475] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=100475] 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-92516").click(function () { $.post("/data/topic/vote", {topicId: 92516, _tta: Codeforces.tta(), topicRevisionId: 229854, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-92516").click(function () { $.post("/data/topic/vote", {topicId: 92516, _tta: Codeforces.tta(), topicRevisionId: 229854, 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:33:26</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:'81289365b9230c42',t:'MTY5NjcwNzIwNi44NDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1540A
1540
A
ru
A. Отличные графы
<div class="problem-statement"><div class="header"><div class="title">A. Отличные графы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Фермера Джона есть ферма, состоящая из $$$n$$$ пастбищ, соединенных с помощью односторонних дорог. У каждой дороги есть вес, означающий время, которое необходимо потратить, чтобы пройти по ней. Дороги могут иметь отрицательный вес, иными словами, коровы по ним движутся так быстро, что способны перемещаться назад во времени! Однако, Фермер Джон гарантирует, что коровы никак не смогут попасть во временную петлю в том смысле, что не смогут, двигаясь по дорогам, уйти бесконечно далеко в прошлое. Кроме того, каждая пара пастбищ соединена не более чем одной дорогой в каждом направлении.</p><p>К сожалению, Фермер Джон потерял карту фермы. Все, что он знает — это массив $$$d$$$, где $$$d_i$$$ — это минимальное время, за которое коровы могут добраться до $$$i$$$-го пастбища из $$$1$$$-го, двигаясь по дорогам. Стоимость его фермы — это сумма весов всех дорог, и Фермер Джон хочет узнать <span class="tex-font-style-bf">минимально</span> возможную стоимость фермы, которая не противоречит тому, что он помнит.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора задано одно целое число $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — количество пастбищ.</p><p>Во второй строке каждого набора заданы $$$n$$$ целых чисел через пробел $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — массив $$$d$$$. Гарантируется, что $$$d_1 = 0$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора, выведите минимально возможную стоимость фермы, которая не противоречит воспоминаниям Фермера Джона.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 0 2 3 2 0 1000000000 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -3 0 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе вы можете добавить дороги </p><ul> <li> от пастбища $$$1$$$ к пастбищу $$$2$$$ с весом $$$2$$$, </li><li> от пастбища $$$2$$$ к пастбищу $$$3$$$ с весом $$$1$$$, </li><li> от пастбища $$$3$$$ к пастбищу $$$1$$$ с весом $$$-3$$$, </li><li> от пастбища $$$3$$$ к пастбищу $$$2$$$ с весом $$$-1$$$, </li><li> от пастбища $$$2$$$ к пастбищу $$$1$$$ с весом $$$-2$$$. </li></ul> Суммарная стоимость равна $$$2 + 1 + -3 + -1 + -2 = -3$$$.<p>Во втором набор вы можете добавить дорогу от пастбища $$$1$$$ к пастбищу $$$2$$$ с весом $$$1000000000$$$ и дорогу от пастбища $$$2$$$ к пастбищу $$$1$$$ со стоимостью $$$-1000000000$$$. Суммарная стоимость равна $$$1000000000 + -1000000000 = 0$$$.</p><p>В третьем наборе, вы не можете добавить ни одной дороги. Суммарная стоимость равна $$$0$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="3abd6472c60b12820688fcfd56713574"/> <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="73d6e96a98bbd7625389194b3afaf471bd9b24fb"/> <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='3abd6472c60b12820688fcfd56713574'>&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%2F1540%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='3abd6472c60b12820688fcfd56713574'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1540">Codeforces Round 728 (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='3abd6472c60b12820688fcfd56713574'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1540/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='3abd6472c60b12820688fcfd56713574'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1027086"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3abd6472c60b12820688fcfd56713574'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1027086"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92093" title="Codeforces Round #728" target="_blank">Codeforces Round #728 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13928" resourceName="Codeforces Round #728" resourceManual="true" src="//codeforces.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/92199" title="Tutorial" target="_blank">Tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13942" 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/1540">Задачи</a></li> <li><a href="/contest/1540/submit">Отослать</a></li> <li><a href="/contest/1540/my">Мои посылки</a></li> <li><a href="/contest/1540/status">Статус</a></li> <li><a href="/contest/1540/hacks">Взломы</a></li> <li><a href="/contest/1540/room/1">Комната</a></li> <li><a href="/contest/1540/standings">Положение</a></li> <li><a href="/contest/1540/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8ca7713b3fb6821cd3f3a9fd9ecbb94dd23bf845"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Отличные графы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Фермера Джона есть ферма, состоящая из $$$n$$$ пастбищ, соединенных с помощью односторонних дорог. У каждой дороги есть вес, означающий время, которое необходимо потратить, чтобы пройти по ней. Дороги могут иметь отрицательный вес, иными словами, коровы по ним движутся так быстро, что способны перемещаться назад во времени! Однако, Фермер Джон гарантирует, что коровы никак не смогут попасть во временную петлю в том смысле, что не смогут, двигаясь по дорогам, уйти бесконечно далеко в прошлое. Кроме того, каждая пара пастбищ соединена не более чем одной дорогой в каждом направлении.</p><p>К сожалению, Фермер Джон потерял карту фермы. Все, что он знает — это массив $$$d$$$, где $$$d_i$$$ — это минимальное время, за которое коровы могут добраться до $$$i$$$-го пастбища из $$$1$$$-го, двигаясь по дорогам. Стоимость его фермы — это сумма весов всех дорог, и Фермер Джон хочет узнать <span class="tex-font-style-bf">минимально</span> возможную стоимость фермы, которая не противоречит тому, что он помнит.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора задано одно целое число $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — количество пастбищ.</p><p>Во второй строке каждого набора заданы $$$n$$$ целых чисел через пробел $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — массив $$$d$$$. Гарантируется, что $$$d_1 = 0$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора, выведите минимально возможную стоимость фермы, которая не противоречит воспоминаниям Фермера Джона.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 0 2 3 2 0 1000000000 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -3 0 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе вы можете добавить дороги </p><ul> <li> от пастбища $$$1$$$ к пастбищу $$$2$$$ с весом $$$2$$$, </li><li> от пастбища $$$2$$$ к пастбищу $$$3$$$ с весом $$$1$$$, </li><li> от пастбища $$$3$$$ к пастбищу $$$1$$$ с весом $$$-3$$$, </li><li> от пастбища $$$3$$$ к пастбищу $$$2$$$ с весом $$$-1$$$, </li><li> от пастбища $$$2$$$ к пастбищу $$$1$$$ с весом $$$-2$$$. </li></ul> Суммарная стоимость равна $$$2 + 1 + -3 + -1 + -2 = -3$$$.<p>Во втором набор вы можете добавить дорогу от пастбища $$$1$$$ к пастбищу $$$2$$$ с весом $$$1000000000$$$ и дорогу от пастбища $$$2$$$ к пастбищу $$$1$$$ со стоимостью $$$-1000000000$$$. Суммарная стоимость равна $$$1000000000 + -1000000000 = 0$$$.</p><p>В третьем наборе, вы не можете добавить ни одной дороги. Суммарная стоимость равна $$$0$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c6be1fb69dab',t:'MTY5NjY2NzM2Ni4yNDMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438 \u043d\u0430 \u0433\u0440\u0430\u0444\u0430\u0445", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1400"]
https://codeforces.com/blog/entry/92199
<!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="ea33d124a1ff874ace73f937748d303e"/> <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="Codeforces Round #728 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #728 Editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='ea33d124a1ff874ace73f937748d303e'>&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%2F92199">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='ea33d124a1ff874ace73f937748d303e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:31:32</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:31:32</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='ea33d124a1ff874ace73f937748d303e'/> <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/PurpleCrayon">PurpleCrayon</a></li> <li class="current selectedLava"><a href="/blog/PurpleCrayon">Blog</a></li> <li><a href="/teams/with/PurpleCrayon">Teams</a></li> <li><a href="/submissions/PurpleCrayon">Submissions</a></li> <li><a href="/groups/with/PurpleCrayon">Groups</a></li> <li><a href="/contests/with/PurpleCrayon">Contests</a></li> <li><a href="/contests/writer/PurpleCrayon">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/PurpleCrayon" style="text-decoration:none;color:black !important;">PurpleCrayon's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="92809"> <div class="title"> <a href="/blog/entry/92199"> <p>Codeforces Round #728 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a>, <a href="/topic/92809/en10">history</a>, <span class="format-humantime" title="Jun/25/2021 20:44">2 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><a href="/contest/1541/problem/A" title="Codeforces Round 728 (Div. 2)">1541A - Pretty Permutations</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The parity (whether $$$n$$$ is odd or even) matters.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Swapping two adjacent cats keeps both of them close to their original location and changes both of their locations.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>If $$$n$$$ is even, the optimal distance is $$$n$$$, and if $$$n$$$ is odd the optimal distance is $$$n+1$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541A">Tutorial is loading...</div></div></div><p><a href="/contest/1541/problem/B" title="Codeforces Round 728 (Div. 2)">1541B - Pleasant Pairs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>$$$i+j \leq 2 \cdot n$$$</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The number of pairs $$$(a, b)$$$ such that $$$a \cdot b \leq x$$$ is $$$O(x log x)$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/A" title="Codeforces Round 728 (Div. 1)">1540A - Great Graphs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What's the minimum value that an edge from $$$a$$$ to $$$b$$$ can be?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use edges with negative value whenever you can.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The sum of the values of edges with positive weight must be $$$\geq$$$ the maximum value in the array.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540A">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Tree Array</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Fix the initial node chosen and root the tree there, what is the contribution of each pair of nodes?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Nothing matters besides the path from node $$$a$$$ to node $$$b$$$, and the initially chosen node $$$r$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>You are given two stacks of size $$$a_1$$$ and $$$a_2$$$. In a single step, you randomly choose a stack to remove a single item from. What is the probability that $$$a_1$$$ becomes $$$0$$$ before $$$a_2$$$? Can you extend this argument for an arbitrary probability $$$p$$$ to remove from one of the two stacks, and a probability of $$$1-2p$$$ to do nothing?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/C2" title="Codeforces Round 728 (Div. 1)">1540C2 - Converging Array (Hard Version)</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What are the invariants? The monovariants?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What is the prefix sum array of the converged array? What is the difference array of the converged array?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you conducted the process on a prefix of size $$$1$$$, then of size $$$2$$$, and on and on?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How many values $$$x$$$ are actually interesting?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540C2">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Inverse Inversions</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The answer is always unique.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Try to figure out what the location of the $$$i$$$-th element would be if you only looked at the first $$$i$$$ elements, then the first $$$i+1$$$, etc. to find an $$$O(nq)$$$ solution.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use sqrt decomposition to optimize it.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540D">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/E" title="Codeforces Round 728 (Div. 1)">1540E - Tasty Dishes</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How much does each chef's initial dish contribute at time $$$k$$$?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you really, really wanted to use matrix exponentiation?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How can you multiply some vectors by a matrix in $$$O(N)$$$ time? (go back to linear algebra class)</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Decompose into linear combinations of eigenvectors.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540E">Tutorial is loading...</div></div></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/1540" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 1)</a> </span> </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/1541" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-191295-92809").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "191295", blogEntryId: "92199", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-92809"><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'>+96</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-92809"><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/PurpleCrayon"><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/PurpleCrayon"> PurpleCrayon </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="Jun/25/2021 20:44">2 years ago</span> </li> <li> <a href="/blog/entry/92199#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/92199#comments"> 170 </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="100805"> <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 (136)</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="808750" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808750" href="?#comment-808750" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808750" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-66" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-66</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808750"> <div class="moveup"> <div class="ttypography"><p>PURPLECRAYON ORZ</p></div> </div> </div> <div class="reply info"> <a class="comment-808750 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808750 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808750"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808751" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hbarp" style="position: relative;"> <img src='https://userpic.codeforces.org/1387715/avatar/c727a810db6ffb66.jpg'/> </a> <div><a href="/profile/hbarp" title="Candidate Master hbarp" class="rated-user user-violet">hbarp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808751" href="?#comment-808751" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808751" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="1387715" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-83</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808751"> <div class="moveup"> <div class="ttypography"><p>Damn, so orz round. <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Мастер PurpleCrayon">PurpleCrayon</a> orz</p></div> </div> </div> <div class="reply info"> <a class="comment-808751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808751"> <li> <div class="comment"> <table class="comment-table" commentId="808805" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/naman1601" style="position: relative;"> <img src='https://userpic.codeforces.org/1703219/avatar/d63fc523dc05fda8.jpg'/> </a> <div><a href="/profile/naman1601" title="Master naman1601" class="rated-user user-orange">naman1601</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808805" href="?#comment-808805" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808805" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-51" data-commentUserId="1703219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-51</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808805"> <div class="moveup"> <div class="ttypography"><p>yeah, amazing problemset, not speedforces at all :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808805 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808805 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808805"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808817" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LOVELY_BOY_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/LOVELY_BOY_" title="Newbie LOVELY_BOY_" class="rated-user user-gray">LOVELY_BOY_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808817" href="?#comment-808817" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-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="808817" 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="808817" class="CommentVoteFrame" data-commentRating="35" data-commentUserId="2089809" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808817"> <div class="moveup"> <div class="ttypography"><p>LOL <a class="rated-user user-blue" href="/profile/hbarp" title="Эксперт hbarp">hbarp</a>,even you didn't participate in the contest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808817 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808817 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808817"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808753" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DontLookBack" style="position: relative;"> <img src='https://userpic.codeforces.org/1534766/avatar/4eacdc5f9758fc28.jpg'/> </a> <div><a href="/profile/DontLookBack" title="Specialist DontLookBack" class="rated-user user-cyan">DontLookBack</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808753" href="?#comment-808753" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808753" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1534766" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808753"> <div class="moveup"> <div class="ttypography"><p>I am curious, how many div2 testers solved D?</p></div> </div> </div> <div class="reply info"> <a class="comment-808753 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808753 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808753"> <li> <div class="comment"> <table class="comment-table" commentId="808826" commentParentId="808753"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/highonjuice" style="position: relative;"> <img src='https://userpic.codeforces.org/1457566/avatar/f7988dd2af03d38b.jpg'/> </a> <div><a href="/profile/highonjuice" title="Pupil highonjuice" class="rated-user user-green">highonjuice</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808826" href="?#comment-808826" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808753" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808826" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1457566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808826"> <div class="moveup"> <div class="ttypography"><p>like 2 ppl, it was hard for me</p></div> </div> </div> <div class="reply info"> <a class="comment-808826 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808826 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808826"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808757" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tlatoani" style="position: relative;"> <img src='https://userpic.codeforces.org/614001/avatar/598b4e8358aad1b4.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/Tlatoani" title="Grandmaster Tlatoani" class="rated-user user-red">Tlatoani</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:18">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808757" href="?#comment-808757" style="font-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="808757" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="808757" class="CommentVoteFrame" data-commentRating="121" data-commentUserId="614001" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+121</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808757"> <div class="moveup"> <div class="ttypography"><h4>Alternate solution to <a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Инвертируем инверсии</a></h4><p>(Read the first nontrivial paragraph of the editorial before reading this alternate solution)</p><p>Let $$$p_r(k) = x$$$ denote that of the numbers $$$p(1), \ldots, p(r)$$$ in sorted order, $$$p(k)$$$ is equal to the $$$x$$$th of these numbers. We will take a decomposition strategy just as the editorial does, though our strategy will be different. We will divide $$$[1, n]$$$ into blocks of length $$$b$$$. For each block covering some interval $$$[l, r]$$$, we will store $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>This means that for any $$$k$$$, if we know $$$p_r(k)$$$ for some block $$$[l, r]$$$, then we can determine $$$p_{r'}(k)$$$ for the block $$$[l', r']$$$ immediately to the right by binary searching on the numbers stored for $$$[l', r']$$$. Therefore, we can perform queries in $$$O\left(\frac n b \lg b\right)$$$.</p><p>We now need to figure out updates. There are probably simple ways to perform updates in $$$O(b\lg b)$$$, but this yields an overall runtime of $$$O(q\sqrt n \lg n)$$$ which is too slow.</p><p>Therefore, we can instead store each block as a segment tree. For each range $$$[l, r]$$$ in the segment tree we store the same thing we store for the whole block: $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>We then have to quickly merge two intervals. We can merge two intervals of length $$$\lambda$$$ in $$$O(\lambda \lg \lambda)$$$ by doing binary search just as we did above, but this still only yields $$$O(b\lg b)$$$ update overall. However, these $$$\lambda$$$ binary searches can be optimized using two pointers to $$$O(\lambda)$$$, making the overall update $$$O(b)$$$.</p><p>We thus have $$$O\left(\frac n b \lg b\right)$$$ query and $$$O(b)$$$ update. Therefore, we can choose $$$b = \sqrt{n\lg n}$$$ to attain an overall runtime of $$$O\left(q\sqrt{n\lg n}\right)$$$ just as the editorial does.</p><p><a href="https://codeforces.com/contest/1540/submission/120611645">Submission in Kotlin</a></p><p><a href="https://codeforces.com/contest/1540/submission/120612729">Submission in C++</a></p><p>It is interesting to note that this solution is quite fast. At the time of writing this update, the C++ version is the fastest correct submission (and runs under 1 second!) and the Kotlin version is faster than the vast majority of submissions.</p></div> </div> </div> <div class="reply info"> <a class="comment-808757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808757"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808765" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardcode229" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardcode229" title="Newbie hardcode229" class="rated-user user-gray">hardcode229</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808765" href="?#comment-808765" style="font-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="808765" 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="808765" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1635180" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808765"> <div class="moveup"> <div class="ttypography"><p>The 3rd hint for the second problem is same as that of the first problem, is it related or a mistake? <strong>UPD:</strong> it is corrected.</p></div> </div> </div> <div class="reply info"> <a class="comment-808765 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808765 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808765"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808769" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/peanut" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/peanut" title="Specialist peanut" class="rated-user user-cyan">peanut</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:24">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808769" href="?#comment-808769" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808769" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="1167233" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+22</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808769"> <div class="moveup"> <div class="ttypography"><p>speedforces.</p></div> </div> </div> <div class="reply info"> <a class="comment-808769 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808769 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808769"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808781" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/graphs_11" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/graphs_11" title="Specialist graphs_11" class="rated-user user-cyan">graphs_11</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808781" href="?#comment-808781" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808781" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1610110" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808781"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">Problem B Detailed Explanation</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808781 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808781 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808781"> <li> <div class="comment"> <table class="comment-table" commentId="809069" commentParentId="808781"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:40">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809069" href="?#comment-809069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808781" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809069" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809069"> <div class="moveup"> <div class="ttypography"><p>Thank you, very well explained</p></div> </div> </div> <div class="reply info"> <a class="comment-809069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809069"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808790" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PC_E1052" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PC_E1052" title="Pupil PC_E1052" class="rated-user user-green">PC_E1052</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808790" href="?#comment-808790" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808790" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="811219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808790"> <div class="moveup"> <div class="ttypography"><p>c was too easy, d was too hard. but d was very nice problem though. </p></div> </div> </div> <div class="reply info"> <a class="comment-808790 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808790 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808790"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808793" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808793" href="?#comment-808793" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808793" class="CommentVoteFrame" data-commentRating="58" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+58</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808793"> <div class="moveup"> <div class="ttypography"><p>Paging <a class="rated-user user-legendary" href="/profile/ecnerwala" title="Легендарный гроссмейстер ecnerwala"><span class="legendary-user-first-letter">e</span>cnerwala</a> to explain his solution to D1E if he'd like. It seems offline?</p></div> </div> </div> <div class="reply info"> <a class="comment-808793 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808793 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808793"> <li> <div class="comment"> <table class="comment-table" commentId="808979" commentParentId="808793"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ecnerwala" 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/ecnerwala" title="Legendary Grandmaster ecnerwala" class="rated-user user-legendary"><span class="legendary-user-first-letter">e</span>cnerwala</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808979" href="?#comment-808979" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808793" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808979" class="CommentVoteFrame" data-commentRating="40" data-commentUserId="57502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808979"> <div class="moveup"> <div class="ttypography"><p>My solution is $$$O(K N^3 + QN)$$$. I just precomputed the coefficient of each $$$a_i$$$ for each prefix-range for each number of days since person $$$i$$$ becomes positive (only $$$1000$$$ possible days) in $$$O(N \cdot K \cdot N^2)$$$, and then summed up the appropriate ones to answer each query in $$$O(N)$$$. It's written in the offline style to use only $$$O(KN)$$$ memory at a time (grouped by $$$a_i$$$) instead of $$$O(KN^2)$$$.</p><p>My passing submission is just $$$KN^3 / 6$$$ instead of the $$$KN^3$$$ I submitted in contest :'(</p><p>If you guys wanted to prevent this, $$$K$$$ could've been much higher, like $$$1e18$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808979 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808979 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808979"> <li> <div class="comment"> <table class="comment-table" commentId="809002" commentParentId="808979"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809002" href="?#comment-809002" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808979" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809002" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809002"> <div class="moveup"> <div class="ttypography"><p>:( I knew of this solution (it’s why ML is tight) but I didn’t realize that it could be done offline with small memory. Of course $$$K$$$ higher is obvious solution but main issue is that the extra modulos from binary exponentiation make it very hard to pass in Java without allowing other unoptimal solutions through such as precomputing inverses of the matrix. Probably $$$k=10^5$$$ would’ve been a better choice. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-809002 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809002 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809002"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808795" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zukonit14" style="position: relative;"> <img src='https://userpic.codeforces.org/1192187/avatar/5afd49be87fb87d9.jpg'/> </a> <div><a href="/profile/zukonit14" title="Expert zukonit14" class="rated-user user-blue">zukonit14</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808795" href="?#comment-808795" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808795" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1192187" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808795"> <div class="moveup"> <div class="ttypography"><p>Does Div2 D deserved to be D Problem? According to me it should've been Div2 E.</p></div> </div> </div> <div class="reply info"> <a class="comment-808795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808795"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808796" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mangat_angad" style="position: relative;"> <img src='https://userpic.codeforces.org/1449578/avatar/d3cadb0c26e0c11f.jpg'/> </a> <div><a href="/profile/mangat_angad" title="Specialist mangat_angad" class="rated-user user-cyan">mangat_angad</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808796" href="?#comment-808796" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808796" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1449578" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808796"> <div class="moveup"> <div class="ttypography"><p>I feel like such an idiot for not being able to understand problem C (Div2). For some reason I thought the nodes were connected like this — 1-&gt;2-&gt;3-&gt;....-&gt;N and that we had to minimise answer by adding other edges (of negative weight in case they dont give a negative cycle) to this graph.</p></div> </div> </div> <div class="reply info"> <a class="comment-808796 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808796 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808796"> <li> <div class="comment"> <table class="comment-table" commentId="808896" commentParentId="808796"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808896" href="?#comment-808896" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808796" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808896" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808896"> <div class="moveup"> <div class="ttypography"><p>But that's exactly what I did, and the final answer is the sum of the array — sum of all subarrays. <a href="https://codeforces.com/contest/1541/submission/120611950">120611950</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808896 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808896 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808896"> <li> <div class="comment"> <table class="comment-table" commentId="808941" commentParentId="808896"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808941" href="?#comment-808941" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808896" style="font-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="808941" 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="808941" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808941"> <div class="moveup"> <div class="ttypography"><p>No, that's not what you did. To compute the answer via the method described above, you would have to compute how many elements are lesser than the current element at any given iteration and add them and also keep and their count using a Fenwick tree/ BIT. That's the incorrect approach though because sorting would be more optimal.</p></div> </div> </div> <div class="reply info"> <a class="comment-808941 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808941 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808941"> <li> <div class="comment"> <table class="comment-table" commentId="808952" commentParentId="808941"> <tr> <td class="left"> <div style="position: absolute; left: 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/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808952" href="?#comment-808952" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808941" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808952" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808952"> <div class="moveup"> <div class="ttypography"><p>Sorry if I misunderstood things. mangat_angad only mentioned adding negative weighed edges to the 1-&gt;2-&gt;3-&gt;...N graph, which is what I thought to arrive at my solution. The array I mentioned is indeed sorted and formed by distance differences which are the weights in the 1-&gt;2-&gt;3-&gt;...N graph. Unfortunately I'm still too noob to understand the tree structures you mentioned.</p></div> </div> </div> <div class="reply info"> <a class="comment-808952 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808952 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808952"> <li> <div class="comment"> <table class="comment-table" commentId="808955" commentParentId="808952"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808955" href="?#comment-808955" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808952" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808955" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808955"> <div class="moveup"> <div class="ttypography"><p>Nothing unfortunate about it, logic trumps everything </p></div> </div> </div> <div class="reply info"> <a class="comment-808955 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808955 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808955"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808797" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808797" href="?#comment-808797" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808797" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808797"> <div class="moveup"> <div class="ttypography"><p>Just want to apologize to authors for the stupidest question, I misread the task..</p></div> </div> </div> <div class="reply info"> <a class="comment-808797 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808797 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808797"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808813" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808813" href="?#comment-808813" style="font-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="808813" 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="808813" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808813"> <div class="moveup"> <div class="ttypography"><p>Can someone tell me the meaning of this line in problem Div2D/Div1B<br /></p> <blockquote><p>Note that, until reaching, l every possible process still has the same probability of reaching b before a. Therefore, we can assume that the process has reached l and calculate the probability from there.</p> </blockquote><p>What same probability are they talking about?</p></div> </div> </div> <div class="reply info"> <a class="comment-808813 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808813 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808813"> <li> <div class="comment"> <table class="comment-table" commentId="808831" commentParentId="808813"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808831" href="?#comment-808831" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808813" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808831" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808831"> <div class="moveup"> <div class="ttypography"><p>Here's what it's trying to say:</p><p>Suppose we start by marking the root. To mark a or b, we must first mark the lca, so we may assume that the lca has just been marked.</p></div> </div> </div> <div class="reply info"> <a class="comment-808831 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808831 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808831"> <li> <div class="comment"> <table class="comment-table" commentId="808840" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808840" href="?#comment-808840" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808840" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808840"> <div class="moveup"> <div class="ttypography"><p>And what does this line mean? <em>&quot;The problem can be rephrased as having two stacks of size dist(l,a) and dist(l,b) with an arbitrary p to remove a node from one of the two stack (and 1−2p to nothing) and finding the probability that dist(l,b) reaches zero before dist(l,a).&quot;</em></p></div> </div> </div> <div class="reply info"> <a class="comment-808840 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808840 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808840"> <li> <div class="comment"> <table class="comment-table" commentId="808857" commentParentId="808840"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808857" href="?#comment-808857" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808840" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808857" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808857"> <div class="moveup"> <div class="ttypography"><p>Once you've reached the lca $$$l$$$, in a single step you either step closer to $$$a$$$, step closer to $$$b$$$, or step closer to neither.</p></div> </div> </div> <div class="reply info"> <a class="comment-808857 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808857 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808857"> <li> <div class="comment"> <table class="comment-table" commentId="808862" commentParentId="808857"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808862" href="?#comment-808862" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808857" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808862" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808862"> <div class="moveup"> <div class="ttypography"><p>Can you add implementation for this problem please?</p></div> </div> </div> <div class="reply info"> <a class="comment-808862 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808862 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808862"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808849" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808849" href="?#comment-808849" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808849" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808849"> <div class="moveup"> <div class="ttypography"><p>So, we mark lca first (of course). But why wouldn't it affect the final probability of reaching b before a? I mean, why is it sufficient to calculate the probability after marking lca?</p></div> </div> </div> <div class="reply info"> <a class="comment-808849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808849"> <li> <div class="comment"> <table class="comment-table" commentId="808873" commentParentId="808849"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808873" href="?#comment-808873" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808849" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808873" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808873"> <div class="moveup"> <div class="ttypography"><p>Before marking the lca, there is no way to make more progress towards $$$b$$$ than $$$a$$$ or vice versa. The subset of marked vertices also does not change the probability of moving towards $$$a$$$ or $$$b$$$ after reaching the lca because we're choosing uniformly at random and exactly two vertices are of interest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808873 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808873 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808873"> <li> <div class="comment"> <table class="comment-table" commentId="808883" commentParentId="808873"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808883" href="?#comment-808883" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808873" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808883" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808883"> <div class="moveup"> <div class="ttypography"><p>Now I get it. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808883 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808883 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808883"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808814" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808814" href="?#comment-808814" style="font-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="808814" 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="808814" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808814"> <div class="moveup"> <div class="ttypography"><p>So, my Solution for <strong>Div1 Problem B</strong> / <strong>Div2 Problem D</strong> / <strong>1540B — Tree Array</strong>:</p><p>Chose two Nodes $$$A$$$ and $$$B$$$ with $$$A&gt;B$$$. </p><p><strong>First DFS:</strong> Find the path from $$$A$$$ to $$$B$$$. I call it $$$path_p$$$. On $$$path_p$$$ mark the distance to $$$B$$$ for each node. </p><p><strong>Second DFS:</strong> For each remaining node $$$N$$$ find the shortest path to $$$path_p$$$. It will hit it at some node of the $$$path_p$$$ which has some distance $$$D$$$ marked on it. We mark $$$N$$$ with $$$D$$$. (See comment below for image.)</p><p><strong>Calculation:</strong> For each node $$$N$$$ we can calculate $$$P_i$$$. $$$P_i$$$ is the probability to reach Node $$$B$$$ before we reach Node $$$A$$$. We sum $$$P_i$$$ for each node. $$$P_i$$$ is also the probability, that the pair of Nodes $$$A$$$ and $$$B$$$ with starting node $$$N$$$ will contribute to the inversion sum. </p><p><strong>Iteration:</strong> We need to repeat this for each pair $$$A$$$ and $$$B$$$. In the end we divide the answer by $$$n$$$, the amount of nodes (the probability to start with Node $$$N$$$). </p><p>This algorithm is $$$O(N^3)$$$. See my Solution <a href="/contest/1540/submission/120603369" title="Посылка 120603369 от OleschY">120603369</a></p> <div class="spoiler"><b class="spoiler-title">How to calculate P_i</b><div class="spoiler-content" style="display: none;"><p>I wrote myself a small helper DP-program to find the regularities. Let $$$D$$$ be the Distance between $$$A$$$ and $$$B$$$ and $$$d$$$ be the distance from the node $$$N$$$ to $$$B$$$. My educated guess was: $$$P_i=\frac{\sum_{i=0}^{d-1}\binom{D-1}{i} }{2^{D-1}}$$$</p> <div class="spoiler"><b class="spoiler-title">Helper Program</b><div class="spoiler-content" style="display: none;"><p>It checks for a path of some length for each Intervall $$$[A,B]$$$ which is already visited, what the probability to reach one node before the other is. </p> <pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; int solve(int n) { vector&lt;vector&lt;double&gt;&gt; dp(n, vector&lt;double&gt;(n, 0)); for(int i = 0; i &lt; n; ++i) { dp[0][i] = 1; dp[i][n - 1] = 0; } dp[0][n - 1] = -1; for(int w = n; w &gt;= 0; w--) { for(int i = 1; i + w &lt; n - 1; i++) { int l = i; int r = w + i; dp[l][r] = 0.5 * (dp[l - 1][r] + dp[l][r + 1]); } } cout &lt;&lt; n &lt;&lt; &quot;\n\n&quot;; for(int i = 0; i &lt; n; i++) { cout &lt;&lt; dp[i][i]*(1&lt;&lt;(n-2)) &lt;&lt; &quot;\n&quot;; } cout &lt;&lt; &quot;\n\n\n\n&quot;; return 0; } //====================== // Technical stuff //====================== int main() { int ntest = 12; for(int test = 2; test &lt; ntest; ++test) { solve(test); } return 0; } </code></pre></div></div></div></div></div> </div> </div> <div class="reply info"> <a class="comment-808814 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808814 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808814"> <li> <div class="comment"> <table class="comment-table" commentId="808843" commentParentId="808814"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808843" href="?#comment-808843" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808814" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808843" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808843"> <div class="moveup"> <div class="ttypography"><p>Can you explain your solution in a little bit more detail? :')</p></div> </div> </div> <div class="reply info"> <a class="comment-808843 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808843 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808843"> <li> <div class="comment"> <table class="comment-table" commentId="808869" commentParentId="808843"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808869" href="?#comment-808869" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808843" style="font-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="808869" 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="808869" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808869"> <div class="moveup"> <div class="ttypography"><p>Oof, I can give you an image, that shows how the distances from the two DFS are distributed on an example. You can see Nodes $$$A$$$ and $$$B$$$ and the numbers are the distances we write into the nodes. </p><p><img alt=" " src="/predownloaded/d8/2f/d82f98ecd2c1b4bd15b3c40e62476f6ae2741a64.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>If you have specific questions about some steps go ahead and ask. </p></div> </div> </div> <div class="reply info"> <a class="comment-808869 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808869 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808869"> <li> <div class="comment"> <table class="comment-table" commentId="810069" commentParentId="808869"> <tr> <td class="left"> <div style="position: absolute; left: 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/Mrajaryan" style="position: relative;"> <img src='https://userpic.codeforces.org/1377953/avatar/e904b3a3a2eac1ad.jpg'/> </a> <div><a href="/profile/Mrajaryan" title="Newbie Mrajaryan" class="rated-user user-gray">Mrajaryan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 15:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810069" href="?#comment-810069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808869" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810069" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1377953" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810069"> <div class="moveup"> <div class="ttypography"><p>what does the dp states mean in your helper program? I am unable to understand. Can you please explain?</p></div> </div> </div> <div class="reply info"> <a class="comment-810069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810069"> <li> <div class="comment"> <table class="comment-table" commentId="810097" commentParentId="810069"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 18:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810097" href="?#comment-810097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-810069" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810097"> <div class="moveup"> <div class="ttypography"><p>You have Nodes $$$1$$$ through $$$N$$$, neighbouring IDs are connected. The state $$$dp[l][r]$$$ is the probability, that node $$$N$$$ will be reached before node $$$1$$$ with all the nodes $$$l$$$ through $$$r$$$ marked already. Obviously $$$dp[1][x]=0$$$ and $$$dp[x][N]=1$$$ ($$$dp[1][N]$$$ can't happen). The recurrence is $$$dp[l][r]=(dp[l-1][r]+dp[l][r+1])/2$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-810097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808818" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808818" href="?#comment-808818" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808818" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808818"> <div class="moveup"> <div class="ttypography"><p>I can't grasp the editorial of Div 2 D/ Div 1 B. Can somebody provide a more intuitive explanation?</p></div> </div> </div> <div class="reply info"> <a class="comment-808818 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808818 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808818"> <li> <div class="comment"> <table class="comment-table" commentId="808821" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:45">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808821" href="?#comment-808821" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808821" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808821"> <div class="moveup"> <div class="ttypography"><p>same :(</p></div> </div> </div> <div class="reply info"> <a class="comment-808821 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808821 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808821"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808861" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808861" href="?#comment-808861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808861" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808861"> <div class="moveup"> <div class="ttypography"><p>Step 1. use linearity of expectation. The answer is</p> <center>$$$\sum_{a&lt;b} P(b\text{ appears before }a). $$$</center><p>Step 2: Observe that if we start by marking a vertex $$$c$$$ on the path between $$$a$$$ and $$$b$$$, and suppose the next marked vertex on the path is $$$d$$$. Then, the probability that $$$d$$$ is between $$$c$$$ and $$$a$$$ and the probability that $$$d$$$ is between $$$c$$$ and $$$b$$$ are both $$$1/2$$$. This is because there are only two choices for $$$d$$$ and we're choosing uniformly at random. This means that the answer only depends on $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p><p>Step 3: run a dp to calculate the probability that we mark $$$b$$$ before $$$a$$$ given $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808861"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808833" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808833" href="?#comment-808833" style="font-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="808833" 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="808833" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-72" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-72</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808833"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin &gt;&gt; t; while(t--){ int n; cin &gt;&gt; n; long long arr[n]; for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0; for(int i = 0; i &lt; n — 1; i++){ for(int j = arr[i] — 2 — i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } } } cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;; } return 0; }</p><p>/* Accepted code A different approach using arrays (as I don't know what vectors are, haven't read that) I hope this is a optimal approach. Any suggestions related to this are whole-heartedly welcomed. Also, please guide me how could I have optimized the code to a much extent. Thanks in advance! Keep programming! */</p></div> </div> </div> <div class="reply info"> <a class="comment-808833 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808833 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808833"> <li> <div class="comment"> <table class="comment-table" commentId="808844" commentParentId="808833"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808844" href="?#comment-808844" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808833" style="font-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="808844" 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="808844" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-35" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808844"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-808844 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808844 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808844"> <li> <div class="comment"> <table class="comment-table" commentId="808863" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808863" href="?#comment-808863" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808863" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808863"> <div class="moveup"> <div class="ttypography"><p>Not studied yet, I'm still a beginner, but planning to start soon. Thanks for the guidance.</p></div> </div> </div> <div class="reply info"> <a class="comment-808863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808863"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808879" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808879" href="?#comment-808879" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808879" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808879"> <div class="moveup"> <div class="ttypography"><p>once upon a time, I also did problems while not know what vectors are. sad times :'(</p></div> </div> </div> <div class="reply info"> <a class="comment-808879 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808879 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808879"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808926" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808926" href="?#comment-808926" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808926" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808926"> <div class="moveup"> <div class="ttypography"><p>There's no issue in not knowing vectors. Yes they are important I agree but not knowing vectors should not be discouraged. I became expert here without knowing anything about vectors plus he is a beginner so he shouldn't be discouraged like this.</p></div> </div> </div> <div class="reply info"> <a class="comment-808926 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808926 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808926"> <li> <div class="comment"> <table class="comment-table" commentId="808927" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Tech.Maniac" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Tech.Maniac" title="Expert Tech.Maniac" class="rated-user user-blue">Tech.Maniac</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808927" href="?#comment-808927" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808927" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1242860" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808927"> <div class="moveup"> <div class="ttypography"><p>+1, I agree with you. Same I was expert last year solely using arrays</p></div> </div> </div> <div class="reply info"> <a class="comment-808927 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808927 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808927"> <li> <div class="comment"> <table class="comment-table" commentId="809201" commentParentId="808927"> <tr> <td class="left"> <div style="position: absolute; left: 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/Yash.Amin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Yash.Amin" title="Specialist Yash.Amin" class="rated-user user-cyan">Yash.Amin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809201" href="?#comment-809201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808927" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809201" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-28" data-commentUserId="1226462" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-28</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809201"> <div class="moveup"> <div class="ttypography"><p>Bas kar bsdk kitna jhooth bolega</p></div> </div> </div> <div class="reply info"> <a class="comment-809201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809201"> <li> <div class="comment"> <table class="comment-table" commentId="809215" commentParentId="809201"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809215" href="?#comment-809215" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809215" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809215"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-blue" href="/profile/Yash.Amin" title="Эксперт Yash.Amin">Yash.Amin</a> Could you please refrain from using foul language on educational discussions. Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-809215 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809215 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809215"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808928" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808928" href="?#comment-808928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808928" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808928"> <div class="moveup"> <div class="ttypography"><p>Ah my bad, I did not want to come across as being arrogant, but I was genuinely confused that some people did not know vectors although they are using C++.</p></div> </div> </div> <div class="reply info"> <a class="comment-808928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808928"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808839" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamkiller04" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dreamkiller04" title="Newbie dreamkiller04" class="rated-user user-gray">dreamkiller04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808839" href="?#comment-808839" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2089608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808839"> <div class="moveup"> <div class="ttypography"><p>Please add implementations too.</p></div> </div> </div> <div class="reply info"> <a class="comment-808839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808839"> <li> <div class="comment"> <table class="comment-table" commentId="809106" commentParentId="808839"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809106" href="?#comment-809106" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808839" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809106" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809106"> <div class="moveup"> <div class="ttypography"><p>Simply running two loops and checking every case would give a TLE. So, we might want to minimize the number of operations. For this, we would only consider the cases where the sum of indices is a multiple of an element.</p><p>For this, we would first create two loops, one within the other, first loop iterating i from 0 to (n — 1) with an incrementation of 1. By observation, we can see that the first index for which the sum of indices will be a multiple of arr[i] is (arr[i] — 2 — i).</p><p>So, in the nested loop we will run j = (arr[i] — 2 — i) till (n — 1) with an incrementation of arr[i]. We would ignore the cases where j &lt; 0 or j &gt;= n.</p><p>Finally, we need to check for how many cases this holds (arr[i] * arr[j] = i + j + 2 and j &gt; i).</p><p>Suggestions are welcomed!</p></div> </div> </div> <div class="reply info"> <a class="comment-809106 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809106 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809106"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808842" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808842" href="?#comment-808842" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808842" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-64" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-64</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808842"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){</p><p>ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);</p><p>int t;</p><p>cin &gt;&gt; t;</p><p>while(t--){</p><p>int n;</p> <pre>cin &gt;&gt; n;</pre><p>long long arr[n];</p> <pre>for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0;</pre><p>for(int i = 0; i &lt; n — 1; i++){</p> <pre>for(int j = arr[i] &amp;mdash; 2 &amp;mdash; i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } }</pre><p>}</p><p>cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;;</p><p>}</p> <pre>return 0;</pre><p>}</p><p>/* Accepted code</p><p>A different approach using arrays (as I don't know what vectors are, haven't read that)</p><p>I hope this is a optimal approach.</p><p>Any suggestions related to this are whole-heartedly welcomed.</p><p>Also, please guide me how could I have optimized the code to a much extent.</p><p>Thanks in advance!</p><p>Keep programming! </p><p>*/</p></div> </div> </div> <div class="reply info"> <a class="comment-808842 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808842 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808842"> <li> <div class="comment"> <table class="comment-table" commentId="808851" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808851" href="?#comment-808851" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808851" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808851"> <div class="moveup"> <div class="ttypography"><p>Use spoilers for writing codes, please!</p></div> </div> </div> <div class="reply info"> <a class="comment-808851 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808851 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808851"> <li> <div class="comment"> <table class="comment-table" commentId="808870" commentParentId="808851"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808870" href="?#comment-808870" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808851" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808870" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808870"> <div class="moveup"> <div class="ttypography"><p>Actually, this is my first comment. Don't know much of this stuff as of now, but I'll surely take care of it the very next time.</p></div> </div> </div> <div class="reply info"> <a class="comment-808870 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808870 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808870"> <li> <div class="comment"> <table class="comment-table" commentId="809760" commentParentId="808870"> <tr> <td class="left"> <div style="position: absolute; left: 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/sus" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sus" title="Pupil sus" class="rated-user user-green">sus</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 05:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809760" href="?#comment-809760" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808870" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809760" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1749651" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809760"> <div class="moveup"> <div class="ttypography"><p>what problem is your code for</p></div> </div> </div> <div class="reply info"> <a class="comment-809760 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809760 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809760"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808884" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sevlll777" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sevlll777" title="Grandmaster sevlll777" class="rated-user user-red">sevlll777</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808884" href="?#comment-808884" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808884" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="839333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808884"> <div class="moveup"> <div class="ttypography"><p>NICE CODESTYLE!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-808884 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808884 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808884"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809084" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cj2021" style="position: relative;"> <img src='https://userpic.codeforces.org/1927237/avatar/b64ff59bd9dcf385.jpg'/> </a> <div><a href="/profile/cj2021" title="Newbie cj2021" class="rated-user user-gray">cj2021</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809084" href="?#comment-809084" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809084" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1927237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809084"> <div class="moveup"> <div class="ttypography"><p>What is &amp;mdash?</p><p>Just curious to know as haven't seen it before.</p></div> </div> </div> <div class="reply info"> <a class="comment-809084 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809084 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809084"> <li> <div class="comment"> <table class="comment-table" commentId="809097" commentParentId="809084"> <tr> <td class="left"> <div style="position: absolute; left: 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/klahsiv" style="position: relative;"> <img src='https://userpic.codeforces.org/1590145/avatar/1bf86ae3d48e55b.jpg'/> </a> <div><a href="/profile/klahsiv" title="Expert klahsiv" class="rated-user user-blue">klahsiv</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809097" href="?#comment-809097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809084" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590145" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809097"> <div class="moveup"> <div class="ttypography"><p>it is minus (-).</p></div> </div> </div> <div class="reply info"> <a class="comment-809097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808848" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/willy108" style="position: relative;"> <img src='https://userpic.codeforces.org/1439320/avatar/d7f79ed4e8b32e9a.jpg'/> </a> <div><a href="/profile/willy108" title="Master willy108" class="rated-user user-orange">willy108</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808848" href="?#comment-808848" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808848" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="1439320" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808848"> <div class="moveup"> <div class="ttypography"><p>Div2 B can also be done in O(NsqrtN). We know that for a given pair of indeces i+j &lt; 2n, so any pair that a[i] * a[j] &lt; 2n will have to have one of the two terms be &lt;= sqrt(n) (with some off by one errors of course). So the algorithm is to store an array of pairs [array value, index] and sort that array by the value. If the array value is &lt;= sqrt(2n) we can naively loop over the rest of the array in O(n) time and check (be careful about overcount), and if the value is &gt; sqrt(n), we can ignore it. This works since when a[i] * a[j] &lt; 2n one of a[i] or a[j] has to be &lt;= sqrt(2n) and as a result, every pair will be counted.</p></div> </div> </div> <div class="reply info"> <a class="comment-808848 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808848 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808848"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808860" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bcollet" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bcollet" title="Master bcollet" class="rated-user user-orange">bcollet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808860" href="?#comment-808860" style="font-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="808860" 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="808860" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="858059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808860"> <div class="moveup"> <div class="ttypography"><p>I don't understand in div1 C why it's prefix of b, in the case i=3 we have $$$a_1+a_2+a_3=f_1+f_1+b_1+f_1+b_1+b_2$$$ so $$$f_1=(ap_i-2b_1-b_2)$$$ I believe the general formula is something in the taste of $$$f_1=(ap_i-ibp_{i-1}+bpt_{i-1})/i$$$ where bpt_i=b_1+2b_2+...+ib_i, I think I miss something<br />Edit: corrected</p></div> </div> </div> <div class="reply info"> <a class="comment-808860 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808860 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808860"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808865" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ParsaS" style="position: relative;"> <img src='https://userpic.codeforces.org/1590150/avatar/dc2d8c002d2c5e1e.jpg'/> </a> <div><a href="/profile/ParsaS" title="Candidate Master ParsaS" class="rated-user user-violet">ParsaS</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808865" href="?#comment-808865" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808865" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590150" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808865"> <div class="moveup"> <div class="ttypography"><p>Nice problems. thanks for almost fast editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-808865 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808865 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808865"> <li> <div class="comment"> <table class="comment-table" commentId="808871" commentParentId="808865"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/E404_Not_Found" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/E404_Not_Found" title="Expert E404_Not_Found" class="rated-user user-blue">E404_Not_Found</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808871" href="?#comment-808871" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808865" style="font-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="808871" 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="808871" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1662858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808871"> <div class="moveup"> <div class="ttypography"><p>Yes thanks for fast editorial :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808871 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808871 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808871"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808890" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vikash_8090_b" style="position: relative;"> <img src='https://userpic.codeforces.org/1969032/avatar/a0f23c893ae54e74.jpg'/> </a> <div><a href="/profile/vikash_8090_b" title="Newbie vikash_8090_b" class="rated-user user-gray">vikash_8090_b</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808890" href="?#comment-808890" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808890" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="1969032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808890"> <div class="moveup"> <div class="ttypography"><p>is there anyone who can't even solve one question of today's contest ..</p></div> </div> </div> <div class="reply info"> <a class="comment-808890 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808890 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808890"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808892" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808892" href="?#comment-808892" style="font-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="808892" 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="808892" class="CommentVoteFrame" data-commentRating="-6" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808892"> <div class="moveup"> <div class="ttypography"><p>Deleted :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808892 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808892 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808892"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808918" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prituladima" style="position: relative;"> <img src='https://userpic.codeforces.org/116750/avatar/ca46d0256a294b26.jpg'/> </a> <div><a href="/profile/prituladima" title="Pupil prituladima" class="rated-user user-green">prituladima</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808918" href="?#comment-808918" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808918" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="116750" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808918"> <div class="moveup"> <div class="ttypography"><p>Please explain div2c/div1a problem a little bit more. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808918 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808918 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808918"> <li> <div class="comment"> <table class="comment-table" commentId="808921" commentParentId="808918"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808921" href="?#comment-808921" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808918" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808921" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808921"> <div class="moveup"> <div class="ttypography"><p>Try out this <a href="https://youtube.com/c/MagentaCobra">channel</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808921 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808921 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808921"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808950" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jakab922" style="position: relative;"> <img src='https://userpic.codeforces.org/53532/avatar/f9515e974f3ebcb1.jpg'/> </a> <div><a href="/profile/jakab922" title="Specialist jakab922" class="rated-user user-cyan">jakab922</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808950" href="?#comment-808950" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808950" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="53532" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808950"> <div class="moveup"> <div class="ttypography"><p>I don't really understand the need for a recursive function for the stack emptying probabilities in <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a>. I mean given that you have a stack of size <code>n</code> and and <code>m</code> you can basically have an array of size <code>n + m</code> filled with <code>0</code>s and <code>1</code>s where <code>0</code> at the <code>i</code>th place means that the <code>i</code>th element was taken from the first stack. Any such array which has <code>n</code> <code>0</code>s and <code>m</code> <code>1</code>s correspond to one process and it's easy to see that whoever takes the last spot in the array gets emptied later which gives an easy way to calculate the probabilities. Namely $$$\binom{n + m - 1}{n - 1} / \binom{n + m}{n}$$$ for the first and similar to the other. </p></div> </div> </div> <div class="reply info"> <a class="comment-808950 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808950 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808950"> <li> <div class="comment"> <table class="comment-table" commentId="808959" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cuom1999" style="position: relative;"> <img src='https://userpic.codeforces.org/253776/avatar/934152bc42a0b10c.jpg'/> </a> <div><a href="/profile/cuom1999" title="Grandmaster cuom1999" class="rated-user user-red">cuom1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808959" href="?#comment-808959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="253776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808959"> <div class="moveup"> <div class="ttypography"><p>If $$$m=2$$$ and $$$n=1$$$, your approach gives $$$\frac{1}{3}$$$. The correct answer should be $$$\frac{1}{4}$$$. </p><p>P/S: I'm also curious if there is any combinatoric approach for this,<a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808959"> <li> <div class="comment"> <table class="comment-table" commentId="809004" commentParentId="808959"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809004" href="?#comment-809004" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809004" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809004"> <div class="moveup"> <div class="ttypography"><p>I would guess that there’s no easy closed form. You can evaluate in $$$O(n)$$$ however by counting right up paths from $$$(a,0)$$$ to $$$(x,y)$$$ for all $$$a$$$ and multiplying by $$$2^{-steps}$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-809004 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809004 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809004"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809366" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/geekpradd" style="position: relative;"> <img src='https://userpic.codeforces.org/367430/avatar/427394aa7f5a63a0.jpg'/> </a> <div><a href="/profile/geekpradd" title="Candidate Master geekpradd" class="rated-user user-violet">geekpradd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809366" href="?#comment-809366" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809366" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="367430" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809366"> <div class="moveup"> <div class="ttypography"><p>The problem with this is that all the possibilities are not equilikely, consider $$$m=2, n=1$$$ and let $$$1$$$ denote entries from the stack of size $$$n$$$. Then the probability of obtaining $$$100$$$ is $$$1/2$$$, while obtaining $$$010$$$ and $$$001$$$ has a probability of $$$1/4$$$. Your approach assumes a uniform prior probability (in which case the answer is indeed $$$1/3$$$ whereas here it is $$$1/4$$$ which is the probability of getting $$$001$$$)</p></div> </div> </div> <div class="reply info"> <a class="comment-809366 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809366 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809366"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thunderboltz" style="position: relative;"> <img src='https://userpic.codeforces.org/1170396/avatar/4f017b259605bc5c.jpg'/> </a> <div><a href="/profile/thunderboltz" title="Newbie thunderboltz" class="rated-user user-gray">thunderboltz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808951" href="?#comment-808951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170396" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808951"> <div class="moveup"> <div class="ttypography"><p>Problem Div2C/Div1A, Plz somebody explain 3rd hint. I didn't get why this condition must be true </p><p><code>The sum of the values of edges with positive weight must be ≥ the maximum value in the array.</code></p></div> </div> </div> <div class="reply info"> <a class="comment-808951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808951"> <li> <div class="comment"> <table class="comment-table" commentId="808995" commentParentId="808951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808995" href="?#comment-808995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808995" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808995"> <div class="moveup"> <div class="ttypography"><p>I like to think about C this way: The cheapest node is the root, and the most expensive node, X, is the one with the highest value, D. Therefore no matter how we make our edges, we need at least 1 path from node to X with distance D. So let's build 1 single edge of positive weight from 1 to X with weight D.</p><p>Now from node X, all other nodes are &lt;= D. We can use negative edges to go there. Now the problem just becomes &quot;assign as many negative edges as possible&quot; to the rest of the nodes. </p></div> </div> </div> <div class="reply info"> <a class="comment-808995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808995"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808971" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808971" href="?#comment-808971" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808971" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808971"> <div class="moveup"> <div class="ttypography"><p>In problem <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a> I agree with everything up to:</p> <blockquote><p>Once l is reached, we now note that the probability that the process &quot;gets closer&quot; to b is always equal to the probability of getting closer to a.</p> </blockquote><p>I agree with this quote if it was about each individual set of marked nodes and single step for them. Because for any individual set of marked nodes, those probabilities is just one over the number of options at the moment. But I don't understand why I should forget about everything else what happens with other parts of tree, because after single step which is neither towards <strong>a</strong> neither towards <strong>b</strong>, the number of options (nodes we can mark on next step) may change.</p></div> </div> </div> <div class="reply info"> <a class="comment-808971 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808971 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808971"> <li> <div class="comment"> <table class="comment-table" commentId="809006" commentParentId="808971"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809006" href="?#comment-809006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808971" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809006" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809006"> <div class="moveup"> <div class="ttypography"><p>That is correct, but to see how it stays the same you can think of it inductively. Use strong induction and assume probability is the same no matter what the state of the tree is. Then from $$$(x,y)$$$ you always have an equal probability of ending up in one of the two states you can transition to because $$$p$$$ is always the same. Every scenario you enter one state, there’s another scenario with the same probability that enters the other state. So, the probability of entering one of the two states is the same as the other, thus $$$0.5$$$. Hopefully that makes things more clear.</p></div> </div> </div> <div class="reply info"> <a class="comment-809006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809006"> <li> <div class="comment"> <table class="comment-table" commentId="809113" commentParentId="809006"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809113" href="?#comment-809113" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809006" style="font-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="809113" 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="809113" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809113"> <div class="moveup"> <div class="ttypography"><p>Oh thanks, it's clear now. So, base of induction is when only <strong>l</strong> reached, and we can show that probability to make step towards <strong>a</strong> and <strong>b</strong> is same because for each individual set you can go from <strong>l</strong> to <strong>b</strong> instead of going from <strong>l</strong> into <strong>a</strong>, using exactly same steps in between (those steps which doesn't change distances to <strong>a</strong> and <strong>b</strong>). And similar holds for next steps.</p></div> </div> </div> <div class="reply info"> <a class="comment-809113 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809113 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809113"> <li> <div class="comment"> <table class="comment-table" commentId="821713" commentParentId="809113"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 08:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821713" href="?#comment-821713" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809113" style="font-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="821713" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="821713" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-821713"> <div class="moveup"> <div class="ttypography"><p>Can you explain this?</p><p>Assume $$$X$$$ is initially node we chose. Then define a function $$$g$$$ :</p><p>$$$g[a][b][STATE]$$$ = probability to reach a before b while state of the tree we reach is $$$STATE$$$, and $$$a$$$, $$$b$$$ is length of path.</p><p><img alt=" " src="/predownloaded/c2/32/c232d053fe3fbd1dedc06e56db58a7c139157987.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>follow the image, I can see : $$$g[a][b][STATE_x] = \frac{1}{4} (g[a][b][STATE_d] + g[a][b][STATE_e] + g[a — 1][b][closer_a] + g[a][b — 1][closer_b])$$$</p><p>It can easy see that the probability can change. Or I wrong in some where?</p></div> </div> </div> <div class="reply info"> <a class="comment-821713 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821713 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821713"> <li> <div class="comment"> <table class="comment-table" commentId="821861" commentParentId="821713"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 18:25">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821861" href="?#comment-821861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821713" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="821861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-821861"> <div class="moveup"> <div class="ttypography"><p>I'll hide my long explanation under spoiler</p> <div class="spoiler"><b class="spoiler-title">horrible wall of text</b><div class="spoiler-content" style="display: none;"><p>To put things into words, I want to define some things. First, suppose we marked some $$$s_1, s_2, s_3 ... s_k$$$ vertices in exact this order. Then, let $$$P(s)$$$ to be probability to mark them in this sequence. It can be decomposed into $$$P(s) = p_1 \cdot p_2 \cdot p_3 \cdot ... \cdot p_k$$$ where $$$p_i = 1/o_{i-1}$$$ where $$$o_i$$$ is number of options at step $$$i$$$ — number of opened vertices, except $$$p_0 = 1/n$$$, or $$$o_0 = n$$$.</p><p>Then, let $$$l = LCA(a, b)$$$ where $$$LCA$$$ is lowest common ancestor. Then, let $$$x_v$$$ to be some sort of 'cost'. For each $$$v$$$ on path between $$$a$$$ and $$$l$$$ it will be distance to $$$l$$$, and $$$-1$$$ everywhere else. Similarly, for each $$$v$$$ on path between $$$b$$$ and $$$l$$$ let $$$y_v$$$ to be distance to $$$l$$$ and $$$-1$$$ everywhere else. Let</p> <center>$$$ A(s) = \max\limits_{v\in s}x_v \\ B(s) = \max\limits_{v\in s}y_v $$$</center><p>Then $$$A(s)$$$ is equal to how far we reach $$$a$$$, and $$$B(s)$$$ is equal to how far we reach $$$b$$$. Let say we are in situation $$$(A(s), B(s))$$$ after marking $$$s$$$, and therefore situation is pair of numbers. Situation $$$(-1,-1)$$$ corresponds that no vertex is marked on path from $$$a$$$ to $$$b$$$. Situation $$$(0,0)$$$ corresponds to only $$$l$$$ marked on path from $$$a$$$ to $$$b$$$. And situation $$$(1,0)$$$ corresponds to $$$l$$$ and single vertex towards $$$a$$$ is marked.</p><p>Finally, let say sequence of marks $$$s$$$ reached state $$$(A(s), B(s))$$$ if either $$$A(s) = x_{s_k}$$$ or $$$B(s) = y_{s_k}$$$, in other words, last vertex is on path from $$$a$$$ to $$$b$$$ and it did change situation.</p><p>Now, what we want to prove is following:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha+1,\beta)} P(s) = \sum\limits_{s\;reached\;(\alpha,\beta+1)} P(s)$$$</center><p><strong>For some fixed</strong> $$$s_1$$$, which is root we chosen. And the way we prove it is that $$$s$$$ that is reached $$$(\alpha+1,\beta)$$$ consists of $$$u$$$ that reached $$$(\alpha,\beta)$$$ plus additional steps: $$$w$$$ plus $$$s_k$$$. So $$$s = u..w..s_k$$$ where $$$..$$$ is concatenation. It's easy to see what none of vertices from $$$w$$$ is on path from $$$a$$$ to $$$b$$$. Also, it's easy to see that we could instead of choosing $$$s_k$$$ could choose vertex $$$z$$$ towards $$$b$$$, and it would have same probability. In other words $$$P(s) = P(u..w..z)$$$. And this $$$u..w..z$$$ should reach state $$$(\alpha, \beta+1)$$$. So it should be in right side sum of our equation we want to prove.</p><p>So, for any $$$s$$$ from left sum, we can make $$$s'$$$ from right sum in unique way, and it will have same $$$P(s) = P(s')$$$. Similarly, for any $$$s$$$ from right sum, we can make $$$s'$$$ from left sum in unique way, and it will have same $$$P(s) = P(s')$$$. So this is bijection, and each element from left sum corresponds to element from right sum with same value, so those sums should have same value. Therefore it's equality.</p><p>Initially I wanted to trim $$$s$$$ from $$$(\alpha+1,\beta)$$$ to $$$(\alpha,\beta)$$$ and show similar thing based on following sum:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha,\beta)} P(s)$$$</center><p>Which is probability to reach state $$$(\alpha, \beta)$$$, but luckily it didn't required. I'll use notation $$$P(reach(\alpha, \beta))$$$ for this probability.</p><p>Thing that is not covered though: why this equality can be translated into probability $$$= 1/2$$$? Well, from $$$(\alpha, \beta)$$$ you eventually will reach either $$$(\alpha+1,\beta)$$$ or $$$(\alpha,\beta+1)$$$, so you can see this as example of Law of total probability. $$$P(reach(\alpha, \beta)) = P(reach (\alpha+1, \beta)) + P(reach (\alpha, \beta+1))$$$, because events $$$(\alpha+1,\beta)$$$ and $$$(\alpha,\beta+1)$$$ are disjoint events given $$$(\alpha, \beta)$$$ is reached. And we proved they have equal probability so $$$P(reach(\alpha, \beta)) = 2\cdot P(reach (\alpha+1, \beta))$$$, so $$$P(reach (\alpha+1, \beta)) = 1/2\cdot P(reach(\alpha, \beta))$$$ which we actually use.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-821861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821861"> <li> <div class="comment"> <table class="comment-table" commentId="822027" commentParentId="821861"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/28/2021 13:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822027" href="?#comment-822027" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821861" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="822027" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822027"> <div class="moveup"> <div class="ttypography"><p>Oh, sorry, there is one missing part. We proved $$$P(reached(\alpha+1,\beta))=P(reached(\alpha,\beta+1))$$$ <strong>given</strong> $$$(\alpha,\beta)$$$ is reached, but this is actually what we need. This <strong>given</strong> condition is what I missed. Without <strong>given</strong> we could reach $$$(\alpha+1,\beta)$$$ from reaching $$$(\alpha+1,\beta-1)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-822027 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822027 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822027"> <li> <div class="comment"> <table class="comment-table" commentId="822370" commentParentId="822027"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 13:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822370" href="?#comment-822370" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822027" style="font-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="822370" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="822370" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822370"> <div class="moveup"> <div class="ttypography"><p>Thanks for amz explain. I realize that I had some missunderstand in the way we calc $$$P(reach\ A\ before\ B)$$$</p><p>This's exactly what in my mind one day ago: let $$$s = ...a...b...$$$ where $$$a$$$ and $$$b$$$ is node $$$a$$$ and node $$$b$$$, &quot;$$$...$$$&quot; mean some node between them which we chose them in exactly that order, or in other word, $$$s$$$ is state represent what we chose (exact in this order) I think $$$P(reach\ A\ before\ B)$$$ (or $$$P(A&lt;B)$$$) must be calculate in this way :</p><p>$$$P(A&lt;B) = \sum_{\substack{all\ s\ which\ a&lt;b}} P(s)$$$</p><p>But unfortunately, it's wrong (may be, or I still missunderstanding)</p><p>$$$P(A) = \sum_{\substack{all\ B[i]\ \subseteq\ A}} P(B[i])$$$ if and only if all $$$B[i]$$$ are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-822370 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822370 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822370"> <li> <div class="comment"> <table class="comment-table" commentId="822755" commentParentId="822370"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 22:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822755" href="?#comment-822755" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822370" style="font-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="822755" 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="822755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822755"> <div class="moveup"> <div class="ttypography"><p>$$$P(A &lt; B)$$$ in your terms is exactly what we need (if a = A and b = B).</p><p>I don't understand last formula, everything else looks fine.</p><p>And to find $$$P(A &lt; B)$$$ we use fact above and calculate all possible ways to reach $$$a$$$ earlier than $$$b$$$ we use $$$(\alpha, \beta)$$$ states using my notation: you either get $$$\alpha$$$ equal to dist to $$$a$$$ when $$$\beta$$$ = 0, or $$$\beta$$$ = 1, or 2, or 3...</p> <center>$$$ P(A &lt; B) = \\ =\sum\limits_{i=0}^{dist(b,l)}P(reach(dist(a,l),i)\;given\; reached(dist(a,l)-1,i)) \\ = \sum\limits_{i=0}^{dist(b,l)}P(reached(dist(a,l)-1,i))\cdot \frac{1}{2} $$$</center><p>Or you can rephrase task into other task with two kind of balls. What probability to remove all balls of one kind earlier than other, if you pick one or other kind of ball with probability 1/2.</p></div> </div> </div> <div class="reply info"> <a class="comment-822755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822755"> </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="808983" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/xsc" style="position: relative;"> <img src='https://userpic.codeforces.org/343/avatar/9eaf243b1eb8c3d4.jpg'/> </a> <div><a href="/profile/xsc" title="Specialist xsc" class="rated-user user-cyan">xsc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808983" href="?#comment-808983" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808983" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="343" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808983"> <div class="moveup"> <div class="ttypography"><p>Div2 D, O(N^4) solution <a href="/contest/1541/submission/120623566" title="Посылка 120623566 от xsc">120623566</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808983 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808983 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808983"> <li> <div class="comment"> <table class="comment-table" commentId="809278" commentParentId="808983"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DavidXu_JJ" style="position: relative;"> <img src='https://userpic.codeforces.org/2003708/avatar/623dc8036b4e9d72.jpg'/> </a> <div><a href="/profile/DavidXu_JJ" title="Expert DavidXu_JJ" class="rated-user user-blue">DavidXu_JJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809278" href="?#comment-809278" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808983" style="font-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="809278" 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="809278" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2003708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809278"> <div class="moveup"> <div class="ttypography"><p>Your code really helps me a lot in debugging,thanks.</p><p>By the way,it's weired that I get Wrong6 when I try to optimize to O(N^3*logN) by binary search on tree.</p><p>I have tested my function on other online judge and my function seems to be correct.</p></div> </div> </div> <div class="reply info"> <a class="comment-809278 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809278 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809278"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809018" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ducati" style="position: relative;"> <img src='https://userpic.codeforces.org/699102/avatar/eff3c352646e914e.jpg'/> </a> <div><a href="/profile/ducati" title="Grandmaster ducati" class="rated-user user-red">ducati</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 03:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809018" href="?#comment-809018" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809018" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="699102" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809018"> <div class="moveup"> <div class="ttypography"><p>Although Div.2 D is harder than ever, in my opinion, it's such a useful and excellent problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-809018 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809018 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809018"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809046" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KanishkGoel" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/KanishkGoel" title="Expert KanishkGoel" class="rated-user user-blue">KanishkGoel</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809046" href="?#comment-809046" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809046" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1917239" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809046"> <div class="moveup"> <div class="ttypography"><p>Is it usual for people to post solutions online during the contest like this channel? <a href="https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ">https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809046 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809046 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809046"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809051" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809051" href="?#comment-809051" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809051"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain why this submission <a href="/contest/1541/submission/120562335" title="Посылка 120562335 от Karnania7201">120562335</a> is failing for Div2 B? It would be a great help.</p></div> </div> </div> <div class="reply info"> <a class="comment-809051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809051"> <li> <div class="comment"> <table class="comment-table" commentId="809076" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809076" href="?#comment-809076" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809076" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809076"> <div class="moveup"> <div class="ttypography"><p>Bro you did not included the condition that i and j should be different i.e (i != j) because it is given in question that no are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-809076 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809076 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809076"> <li> <div class="comment"> <table class="comment-table" commentId="809079" commentParentId="809076"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:08">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809079" href="?#comment-809079" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809076" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809079" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809079"> <div class="moveup"> <div class="ttypography"><p>I think its covered as I started j from i+1. I tried that explicitly too but it didn't work. I wrote the same idea in a different way and it worked but this kind of implementation is not working.</p></div> </div> </div> <div class="reply info"> <a class="comment-809079 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809079 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809079"> <li> <div class="comment"> <table class="comment-table" commentId="809082" commentParentId="809079"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809082" href="?#comment-809082" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809079" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809082" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809082"> <div class="moveup"> <div class="ttypography"><p>yeah, you are right, I run your code using vector instead of creating memeset it worked fine, i guess there is some problem in that. <a href="https://codeforces.com/contest/1541/submission/120633207">120633207</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809082 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809082 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809082"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809081" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_NICkk" style="position: relative;"> <img src='https://userpic.codeforces.org/1543175/avatar/6084dd87f2c1cad9.jpg'/> </a> <div><a href="/profile/_NICkk" title="Expert _NICkk" class="rated-user user-blue">_NICkk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809081" href="?#comment-809081" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809081" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1543175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809081"> <div class="moveup"> <div class="ttypography"><p>Only fault in your code is that you didn't used memset correctly </p><p>I just changed your memset with this &quot; memset(ind, 0, sizeof(ind)) &quot; and it worked perfectly fine</p></div> </div> </div> <div class="reply info"> <a class="comment-809081 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809081 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809081"> <li> <div class="comment"> <table class="comment-table" commentId="809091" commentParentId="809081"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:37">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809091" href="?#comment-809091" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809081" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809091" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809091"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot to both of you. I shouldn't have used it without properly knowing about it. </p></div> </div> </div> <div class="reply info"> <a class="comment-809091 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809091 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809091"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809064" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vrintle" style="position: relative;"> <img src='https://userpic.codeforces.org/1991777/avatar/24d9007095afbbb6.jpg'/> </a> <div><a href="/profile/vrintle" title="Master vrintle" class="rated-user user-orange">vrintle</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809064" href="?#comment-809064" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809064" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1991777" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809064"> <div class="moveup"> <div class="ttypography"><p>Instead of $$$a_i \cdot a_j \leq 2n$$$, we could also check $$$a_i \cdot a_j \leq i+n$$$ which is a bit faster ($$$ \sim 62ms$$$).</p></div> </div> </div> <div class="reply info"> <a class="comment-809064 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809064 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809064"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809066" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809066" href="?#comment-809066" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809066" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809066"> <div class="moveup"> <div class="ttypography"><p>can anyone explain B. pleasant pairs more easy words?? </p></div> </div> </div> <div class="reply info"> <a class="comment-809066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809066"> <li> <div class="comment"> <table class="comment-table" commentId="809067" commentParentId="809066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809067" href="?#comment-809067" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809067" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809067"> <div class="moveup"> <div class="ttypography"><p>And also what is ask in 3rd question i cant understand what asked in it</p></div> </div> </div> <div class="reply info"> <a class="comment-809067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809067"> <li> <div class="comment"> <table class="comment-table" commentId="809070" commentParentId="809067"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809070" href="?#comment-809070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809067" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809070"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">https://www.youtube.com/watch?v=xCj_ZR5kENo</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809098" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809098" href="?#comment-809098" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809098" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809098"> <div class="moveup"> <div class="ttypography"><p>For those who are searching for a simple solution for great Graphs problems in O (nlogn). <a href="https://codeforces.com/contest/1541/submission/120600816">https://codeforces.com/contest/1541/submission/120600816</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809098 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809098 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809098"> <li> <div class="comment"> <table class="comment-table" commentId="809119" commentParentId="809098"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fjvzr" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/fjvzr" title="Newbie fjvzr" class="rated-user user-gray">fjvzr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809119" href="?#comment-809119" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809098" style="font-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="809119" 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="809119" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1623986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809119"> <div class="moveup"> <div class="ttypography"><p>Bro can u explain this soln????? i thought of taking all pairs that give negative edges except for the adjacent pairs.... bt getting wrong ans in 3rd 4th test case.....</p><p>while(n&gt;2) { sum-=(n-2)*(llabs(a[j]-a[i])); n--; // n = size i++; // i = 0 j--; // j = n-1 } cout&lt;&lt;sum&lt;&lt;endl;</p><p><a href="https://codeforces.com/contest/1541/submission/120636509">mysoln</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809119 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809119 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809119"> <li> <div class="comment"> <table class="comment-table" commentId="809124" commentParentId="809119"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809124" href="?#comment-809124" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809119" style="font-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="809124" 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="809124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809124"> <div class="moveup"> <div class="ttypography"><p>My solution is simple. First sort the array. </p><p>Then start connecting adjacent values with their differences. This way sum of all edges with positive weight will be same as the sum of adjacent differences in the array.</p><p>After that start making negative edges for every i. So each i will have i negative edges. Where negative weight is same as -(arr[i] — arr[j]).</p><p>Instead of search it for every j I have formula as (prefixsum till i) — arr[i]*i</p></div> </div> </div> <div class="reply info"> <a class="comment-809124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809124"> <li> <div class="comment"> <table class="comment-table" commentId="809132" commentParentId="809124"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809132" href="?#comment-809132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809124" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809132"> <div class="moveup"> <div class="ttypography"><p>can you tell me why are we sorting the array for a particular node call it x we need to add a negative weight from x to 1 , x to 2 x to 3 till x to x-1 keeping in mind the the path sum doesn't become negative so why are we sorting the array</p></div> </div> </div> <div class="reply info"> <a class="comment-809132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809132"> <li> <div class="comment"> <table class="comment-table" commentId="809135" commentParentId="809132"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809135" href="?#comment-809135" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809135" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809135"> <div class="moveup"> <div class="ttypography"><p>We are sorting values only once so as to connect neighboring nodes with minimum values,i.e. difference b/w consecutive values.<br /> From this sum of positive edges will be minimum.</p></div> </div> </div> <div class="reply info"> <a class="comment-809135 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809135 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809135"> <li> <div class="comment"> <table class="comment-table" commentId="809139" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809139" href="?#comment-809139" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809139" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809139"> <div class="moveup"> <div class="ttypography"><p>ohhh thanks I got it</p></div> </div> </div> <div class="reply info"> <a class="comment-809139 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809139 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809139"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809145" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809145" href="?#comment-809145" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809145" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809145"> <div class="moveup"> <div class="ttypography"><p>My solution is working now I only needed to sort the array my code would have been accepted during the contest :(</p></div> </div> </div> <div class="reply info"> <a class="comment-809145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809145"> </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="809116" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ken_KaNeKi_997" style="position: relative;"> <img src='https://userpic.codeforces.org/1737228/avatar/50ceb845253df5d4.jpg'/> </a> <div><a href="/profile/Ken_KaNeKi_997" title="Newbie Ken_KaNeKi_997" class="rated-user user-gray">Ken_KaNeKi_997</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809116" href="?#comment-809116" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809116" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1737228" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809116"> <div class="moveup"> <div class="ttypography"><p>can anyone explain div2 B plz</p></div> </div> </div> <div class="reply info"> <a class="comment-809116 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809116 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809116"> <li> <div class="comment"> <table class="comment-table" commentId="809204" commentParentId="809116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809204" href="?#comment-809204" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809116" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809204" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809204"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/92199#comment-809178">here</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809204 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809204 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809204"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809122" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809122" href="?#comment-809122" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809122" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809122"> <div class="moveup"> <div class="ttypography"><p>Beautiful Problems. Amazing Round!!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-809122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809122"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809156" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dummybawa" style="position: relative;"> <img src='https://userpic.codeforces.org/1704408/avatar/1522f670cd21321.jpg'/> </a> <div><a href="/profile/dummybawa" title="Expert dummybawa" class="rated-user user-blue">dummybawa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809156" href="?#comment-809156" style="font-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="809156" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809156" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1704408" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809156"> <div class="moveup"> <div class="ttypography"><p>UPD: It's wrong. </p></div> </div> </div> <div class="reply info"> <a class="comment-809156 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809156 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809156"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809178" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809178" href="?#comment-809178" style="font-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="809178" 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="809178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809178"> <div class="moveup"> <div class="ttypography"><p>For DIV 2C/1A can anyone explain with this test case N = 6 and D = 0 1 2 3 2 3. What are the edges that we can have with their weights?</p></div> </div> </div> <div class="reply info"> <a class="comment-809178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809178"> <li> <div class="comment"> <table class="comment-table" commentId="809198" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Zemrith" style="position: relative;"> <img src='https://userpic.codeforces.org/1159882/avatar/2a6566e372882267.jpg'/> </a> <div><a href="/profile/Zemrith" title="Expert Zemrith" class="rated-user user-blue">Zemrith</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809198" href="?#comment-809198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-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="809198" 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="809198" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159882" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809198"> <div class="moveup"> <div class="ttypography"><p>Hello! The answer would be -18.</p><p>Diagram: <img alt=" " src="/predownloaded/8c/88/8c88a0230dea9f499896ee59def659611c605976.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Notice that once you sort the distances, the adjacent nodes have no effect on your final answer. But you can add negative edges as long as they are not adjacent, resulting in such a diagram. Hence you can use prefix sums to solve the problem. (if x nodes came before this, for each node, the answer to add is (x-1)*curr value — csum of first (x-1) nodes). </p><p>Hope that made sense!</p></div> </div> </div> <div class="reply info"> <a class="comment-809198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809198"> <li> <div class="comment"> <table class="comment-table" commentId="809218" commentParentId="809198"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:27">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809218" href="?#comment-809218" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809218" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809218"> <div class="moveup"> <div class="ttypography"><p>Thank you <a class="rated-user user-cyan" href="/profile/Zemrith" title="Специалист Zemrith">Zemrith</a> for so much detail explanation and the solution too it helped me a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-809218 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809218 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809218"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809199" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809199" href="?#comment-809199" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809199" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809199"> <div class="moveup"> <div class="ttypography"><p>first sort the array they will from non negative weight edges. 0 -&gt; 1 -&gt; 2 -&gt; 2 -&gt; 3 -&gt; 3 so the non negative weights will be 1 | 1 | 0 | 1 | 0. form here greedily build most negative weights(backward edges) such that there are no negative cycles.</p></div> </div> </div> <div class="reply info"> <a class="comment-809199 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809199 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809199"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809203" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809203" href="?#comment-809203" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809203" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809203"> <div class="moveup"> <div class="ttypography"><p>First you can sort D and get: <code> N = 6, D = [0, 1, 2, 2, 3, 3] </code></p><p>Now calculate the diffs:</p><p><code>diffs = [1, 1, 0, 1, 0]</code></p><p>The edges for this graph could be something like this:</p> <pre><code> 1 1 0 1 0 &lt;- forward edges 1 &lt;-&gt; 2 &lt;-&gt; 3 &lt;-&gt; 4 &lt;-&gt; 5 &lt;-&gt; 6 -1 -1 0 -1 0 &lt;- backward edges </code></pre><p>Now you have to add more negatives edges, and you could do this by choosing some <code>i</code> and <code>j</code>, <code>i &lt; j</code> and add an edges from <code>j</code> to <code>i</code>, and the weight will be sum of the values from <code>diff[i]</code> to <code>diff[j]</code>.</p><p>Another way to think about this is: look at <code>D</code> array, it represents distances between adjacent nodes, all we have to do is add all of the edges with length 2, then all of the edges of length 3, ..., all of the edges of length <code>N - 1</code>.</p><p>So, for our case we would have these edges</p> <pre><code>a b W ------- 1 2 - 1 2 3 - 1 3 4 - 0 &lt;- adjacent forward edges 4 5 - 1 5 6 - 0 2 1 - -1 3 2 - -1 4 3 - 0 &lt;- adjacent backward edges 5 4 - -1 6 5 - 0 3 1 - -2 4 2 - -1 5 3 - -1 &lt;- edges of length 2 6 4 - -1 4 1 - -2 5 2 - -2 &lt;- edges of length 3 6 3 - -1 5 1 - -3 6 2 - -2 &lt;- edges of length 4 6 1 - -3 &lt;- edges of length 5 </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809203 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809203 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809203"> <li> <div class="comment"> <table class="comment-table" commentId="809221" commentParentId="809203"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809221" href="?#comment-809221" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809203" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809221" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809221"> <div class="moveup"> <div class="ttypography"><p>Thank You <a class="rated-user user-green" href="/profile/ilidar" title="Ученик ilidar">ilidar</a> for clearing my doubt and for detailed explaination.</p></div> </div> </div> <div class="reply info"> <a class="comment-809221 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809221 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809221"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809280" href="?#comment-809280" style="font-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="809280" revisionCount="7" revision="7"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">7</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809280" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+18</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809280"> <div class="moveup"> <div class="ttypography"><p>Could someone please provide a more strict intuition or insight of Div2D/Div1B of why &quot;the actual probability p does not matter&quot;? The intuition in the editorial is still alien to me of why those choices of not progess toward to either stacks (and probability 'p' also changes from time to time too) doesn't matter.</p><p>Update: Here is the intuition I came up with (The strict proof can be found in the comment of the author below)</p><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left) in some states of the current tree.</p><p>now, we will try break this $$$dp_{i,j}$$$ down into the sum of $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$</p><p>We will try to illustrate this with trying to split and color, either red or blue, a stick of length $$$1$$$. The length of the sticks representing the 'probability', and the color of the sticks will represent $$$dp_{i-1,j}$$$(red) or $$$dp_{i,j-1}$$$(blue), depending on the color.</p><p>Suppose in the current state, we have probability $$$p$$$ for choosing to pop each stacks, and the rest $$$1-2p$$$ of doing nothing. The picture will look like this:</p><p><a href="https://ibb.co/q9HjQTm"><img alt="Tree-Array-Rep" border="0" src="/predownloaded/13/57/135732d2b0967af0f76c1dba28df72086f234c7d.png" style="max-width: 100.0%;max-height: 100.0%;" /></a></p><p>We will split the stick equally(*) into several sticks of length $$$p$$$, and then color two of them red and blue. (* We can split it evenly because in the original problem, $$$p$$$ is in the form $$$\frac{1}{number\ of\ candidate\ unmark\ nodes}$$$ ) Now, the remaining sticks represent the state of $$$dp_{i,j}$$$ again (in some other state of the entire tree, so might be in some different $$$p$$$). That means we will split those sticks similary.</p><p>The key observations is:</p><p>1) We know that, in the original problem, if we keep picking nodes that aren't progressing toward the target nodes, we will run out of nodes eventually and finally choose the two nodes. That means, all the sticks will eventually colored into 'red' and 'blue'.</p><p>2) When we split a stick into several smaller equal length sticks, we will color two of them into red and blue. <strong>Those two sticks always have the same length</strong>. That means, the total length of blue sticks and the total length of red sticks will be equal in the end.</p><p>Analogically, that means, eventually, $$$dp_{i,j}$$$ will split into $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$ evenly, no matter $$$p$$$ might be or the state of tree of $$$dp_{i,j}$$$ might be. Therefore, $$$dp_{i,j} = \frac{1}{2} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-809280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809280"> <li> <div class="comment"> <table class="comment-table" commentId="809284" commentParentId="809280"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809284" href="?#comment-809284" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809280" style="font-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="809284" 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="809284" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809284"> <div class="moveup"> <div class="ttypography"><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left), with having arbitary probability $$$0 &lt; p \leq 0.5$$$ of chosing to pick the top of each stack (and $$$1-2p$$$ for doing nothing). Then</p><p>$$$dp_{i,j}=\int_{0}^{0.5} x \cdot (dp_{i-1,j}+dp_{i,j-1}) + (1-2x) \cdot dp_{i,j} \,dx$$$</p><p>Solving the equation, we get $$$dp_{i,j}=\frac{1}{6} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$ What is the mistake in this logic?</p></div> </div> </div> <div class="reply info"> <a class="comment-809284 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809284 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809284"> <li> <div class="comment"> <table class="comment-table" commentId="809399" commentParentId="809284"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809399" href="?#comment-809399" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809284" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809399" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809399"> <div class="moveup"> <div class="ttypography"><p>The biggest issue with this logic is that it's assuming $$$p$$$ is arbitrary chosen from a certain state. While $$$p$$$ can be anything in the world, it is always an exact number from a certain state, hence why an integral is wrong. </p><p>As a different type of intuition, you can think, &quot;is it more likely to reach $$$(i-1, j)$$$ than state $$$(i, j-1)$$$&quot;? and vice versa. For me at least, I don't see how it's possible for either of those questions to be true, so they should be equal.</p><p>If you're looking for a more rigorously correct $$$dp$$$, it would look something like this.</p> <div class="spoiler"><b class="spoiler-title">Proof</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp_{i, j, S}$$$ denote the probability of reaching some node $$$i$$$ distance away before some node $$$j$$$ distance away where $$$S$$$ is a representation of the entire state of of the process (not necessarily an integer). I think you already understood why we can assume the $$$lca$$$ is already reached. We aim to show that $$$S$$$ does not matter in our calculation. Assume inductively that $$$S$$$ does not matter. So, we can assume that states $$$(i-1, j)$$$ and states $$$(i, j-1)$$$ are irrelevant to $$$S$$$. Hence, the part we need to care about is $$$(1-2p) dp_{i, j, S \rightarrow S_a}$$$. A way of thinking about this part of the transition is moving through the collection of $$$S$$$ with the state $$$(i, j)$$$. Obviously, the $$$dp$$$ is a $$$DAG$$$ because no state $$$S$$$ can reach another. Each bounce takes a certain probability $$$p$$$ which is just multiplied in the current path. So, for each state $$$S$$$ with state $$$(i, j)$$$, we have a certain probability to reach it by simply calculating $$$dp$$$ along a DAG as is traditional. Then, from those states of $$$(i, j)$$$ you transition to $$$(i, j-1)$$$ with an equal probability $$$(i-1, j)$$$. So, they have to be equal. Finally, this argument holds for any initial state $$$S$$$ that you reach, so we can conclude that, from any state $$$S$$$ with a state of $$$(i, j)$$$, the probability of transitions to $$$(i-1, j)$$$ and $$$(i, j-1)$$$ are always exactly $$$0.5$$$.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-809399 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809399 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809399"> <li> <div class="comment"> <table class="comment-table" commentId="809701" commentParentId="809399"> <tr> <td class="left"> <div style="position: absolute; left: 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/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809701" href="?#comment-809701" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809399" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809701" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809701"> <div class="moveup"> <div class="ttypography"><p>I see, thank you so much!</p></div> </div> </div> <div class="reply info"> <a class="comment-809701 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809701 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809701"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809298" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/satyam_singh93" style="position: relative;"> <img src='https://userpic.codeforces.org/1763011/avatar/9d9fa405de19ab0e.jpg'/> </a> <div><a href="/profile/satyam_singh93" title="Newbie satyam_singh93" class="rated-user user-gray">satyam_singh93</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809298" href="?#comment-809298" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809298" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1763011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809298"> <div class="moveup"> <div class="ttypography"><p>I am getting wrong ans . could someone tell me where the code make differene ( [yestrday competiton problem .</p><p>`](<a href="https://codeforces.com/contest/1541/problem/B)">https://codeforces.com/contest/1541/problem/B)</a>.</p> <pre><code>int main( ) { clock_t begin = clock(); file_i_o(); // Write your code here.... int t; cin&gt;&gt;t; while(t-- ){ int n; cin&gt;&gt;n; vector&lt;pair&lt;int,int&gt;&gt;v; v.push_back({0,0}); loop(i,0,n) { int x; cin&gt;&gt;x; v.pb({x,i+1}); } sort(v.begin()+1,v.end()); int count =0; for(int i=1 ; i&lt;=n;i++) { for(ll j=i+1;j&lt;=n;j++) { ll left = v[i].first * v[j].first; ll right = v[i].second + v[j].second; if(left == right) count++; if(left &gt; 2*n ) break; } } cout&lt;&lt;count&lt;&lt;endl; } </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809298 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809298 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809298"> <li> <div class="comment"> <table class="comment-table" commentId="809305" commentParentId="809298"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809305" href="?#comment-809305" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809298" style="font-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="809305" 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="809305" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809305"> <div class="moveup"> <div class="ttypography"><p>v[i].first * v[j].first can create overflow. So, you need to convert them to long long by using</p><p>ll left = 1LL * v[i].first * v[j].first;</p><p>instead and it would pass.</p><p>(Simply save the value in long long won't help. You need to convert them to long long before doing multiplication. 1LL* is one way)</p></div> </div> </div> <div class="reply info"> <a class="comment-809305 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809305 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809305"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809309" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809309" href="?#comment-809309" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809309" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809309"> <div class="moveup"> <div class="ttypography"><p>Hi, in problem Div1.B/Div2.D; I can't wrap my head around $$$F[x][y]=F[x−1][y]/2+F[x][y−1]/2$$$. Why is it not $$$F[x][y]=F[x−1][y+1]/2+F[x+1][y−1]/2$$$, can someone please explain to me why is my transition wrong and/or why is the aforementioned transition correct? </p></div> </div> </div> <div class="reply info"> <a class="comment-809309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809309"> <li> <div class="comment"> <table class="comment-table" commentId="809311" commentParentId="809309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809311" href="?#comment-809311" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809311" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809311"> <div class="moveup"> <div class="ttypography"><p>x and y is the distance left for each side right? So, if you take one out, it won't make sense to add that one to the other side since the distance should be either x-1 and y or x and y-1.</p></div> </div> </div> <div class="reply info"> <a class="comment-809311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809311"> <li> <div class="comment"> <table class="comment-table" commentId="809339" commentParentId="809311"> <tr> <td class="left"> <div style="position: absolute; left: 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/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809339" href="?#comment-809339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809339" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809339"> <div class="moveup"> <div class="ttypography"><p>Thank you so much I understand. I had a minor misunderstanding of the parameters to the dp state.</p></div> </div> </div> <div class="reply info"> <a class="comment-809339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809339"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809371" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:13">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809371" href="?#comment-809371" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809371" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809371"> <div class="moveup"> <div class="ttypography"><p>PLease explain why 2 same codes are not giving the same ans</p><p>code forces round 728 div2<br />Problem B :<a href="https://codeforces.com/contest/1541/problem/B">https://codeforces.com/contest/1541/problem/B</a></p><p>AC Submission : <a href="https://ide.codingblocks.com/s/579769">https://ide.codingblocks.com/s/579769</a></p><p>Wrong output Submission :<a href="https://ide.codingblocks.com/s/579771">https://ide.codingblocks.com/s/579771</a></p><p>Difference is using of macro (node) instead of pair&lt;int,int&gt; </p><p>Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-809371 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809371 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809371"> <li> <div class="comment"> <table class="comment-table" commentId="809379" commentParentId="809371"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809379" href="?#comment-809379" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809371" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809379" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809379"> <div class="moveup"> <div class="ttypography"><p>If i am using #define node pair&lt;int,int&gt; it is getting accepted but when i am using typedef pair&lt;int,int&gt; node; it is giving wrong answer</p><p>Why this is happening ?? Is it a bug??</p></div> </div> </div> <div class="reply info"> <a class="comment-809379 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809379 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809379"> <li> <div class="comment"> <table class="comment-table" commentId="809407" commentParentId="809379"> <tr> <td class="left"> <div style="position: absolute; left: 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/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 19:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809407" href="?#comment-809407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809379" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809407" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809407"> <div class="moveup"> <div class="ttypography"><p>Not really sure why this is happening.</p><p>However, I think the problem is the position of #define int long long. So, for #define pair&lt;int,int&gt; node it seems that compiler change node -&gt; pair&lt;int,int&gt; -&gt; pair&lt;long long, long long&gt;. However, when you do typedef, it still keeps in pair&lt;int, int&gt; which creates an overflow problem later on. </p><p>I did try moving #define int long long up above typedef and the code pass. So, my best guess is #define int long long only replace int after that position with long long. Thus, node is still pair&lt;int, int&gt; in the typedef solution, while node is changed to pair&lt;long long, long long&gt; in the second solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-809407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809407"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809627" href="?#comment-809627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809627"> <div class="moveup"> <div class="ttypography"><p>May I ask why in the Div1D solution ci=i-bi, I think it should be ci=bi ...</p></div> </div> </div> <div class="reply info"> <a class="comment-809627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809627"> <li> <div class="comment"> <table class="comment-table" commentId="809631" commentParentId="809627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809631" href="?#comment-809631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809631" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809631"> <div class="moveup"> <div class="ttypography"><p>Check the definition of bi again dude. bi here means <strong>number of elements greater than pi</strong>. So to get ci, which is <strong>number of elements smaller than pi</strong>, you need i-bi.</p></div> </div> </div> <div class="reply info"> <a class="comment-809631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809631"> <li> <div class="comment"> <table class="comment-table" commentId="809636" commentParentId="809631"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809636" href="?#comment-809636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809636"> <div class="moveup"> <div class="ttypography"><p>I read it again. If I read it correctly, bi stands for j&lt;i,pj&gt;pi, and ci stands for j&gt;i,pj&lt;pi. For example, p={1,3,5,4,6,2}, I think b4=1,c4=1, please point out my problem</p></div> </div> </div> <div class="reply info"> <a class="comment-809636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809636"> <li> <div class="comment"> <table class="comment-table" commentId="809638" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809638" href="?#comment-809638" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809638" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809638"> <div class="moveup"> <div class="ttypography"><p>oh, the array index starts from 1</p></div> </div> </div> <div class="reply info"> <a class="comment-809638 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809638 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809638"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809639" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809639" href="?#comment-809639" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809639" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809639"> <div class="moveup"> <div class="ttypography"><p>You are right.</p><p>I guess it might just be typo and ci stands for j&lt;i, pj&lt;pi. At least with this definition of ci the algorithm seems correct :)</p></div> </div> </div> <div class="reply info"> <a class="comment-809639 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809639 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809639"> <li> <div class="comment"> <table class="comment-table" commentId="809641" commentParentId="809639"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809641" href="?#comment-809641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809639" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809641"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-809641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809641"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809705" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/darthrevenge" style="position: relative;"> <img src='https://userpic.codeforces.org/1567000/avatar/ee31d2a91a9575b9.jpg'/> </a> <div><a href="/profile/darthrevenge" title="Candidate Master darthrevenge" class="rated-user user-violet">darthrevenge</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809705" href="?#comment-809705" style="font-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="809705" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809705" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1567000" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809705"> <div class="moveup"> <div class="ttypography"><p>Here's my solution of B div 1 / D div 2 without LCA, using single DFS per node. <a href="/contest/1540/submission/120700765" title="Посылка 120700765 от darthrevenge">120700765</a> It is similar to what <a class="rated-user user-violet" href="/profile/OleschY" title="Кандидат в мастера OleschY">OleschY</a> suggested above. I've tried to describe it in the <a href="https://codeforces.com/blog/entry/92284">blog</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-809705 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809705 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809705"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809951" href="?#comment-809951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809951"> <div class="moveup"> <div class="ttypography"><p>Can someone explain how you can find the LCA for each pair so quick? Iterating through every root is and then considering every pair is already N^3</p></div> </div> </div> <div class="reply info"> <a class="comment-809951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809951"> <li> <div class="comment"> <table class="comment-table" commentId="809965" commentParentId="809951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PurpleCrayon" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809965" href="?#comment-809965" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809965" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="1604355" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809965"> <div class="moveup"> <div class="ttypography"><p>There are a couple ways you could do it:</p> <ol> <li>Just use standard binary lifting (initialize once for each root). This runs in $$$\mathcal{O}(n^3 \log{}n)$$$, and should pass under the given constraints. You could also just use $$$\mathcal{O}(1)$$$ lca using an rmq over an euler tour.</li> <li>You could use a version of dp, where $$$dp[a][b] = lca(a, b)$$$. If the depth of $$$a$$$ is greater than the depth of $$$b$$$, $$$dp[a][b] = dp[parent[a]][b]$$$, otherwise $$$dp[a][b] = dp[a][parent[b]]$$$. The base cases are $$$dp[a][a] = a$$$ for all $$$a$$$. This runs in $$$\mathcal{O}(n^3)$$$.</li> <li>You could extend this idea and do the main solution's dp directly on the tree (without ever worrying about lca's). The recurrence is equivalent to the main solution ($$$dp[a][b] = \frac{dp[parent[a]][b]+dp[a][parent[b]]}{2}$$$ with the base cases being one node is an ancestor of the other.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-809965 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809965 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809965"> <li> <div class="comment"> <table class="comment-table" commentId="809967" commentParentId="809965"> <tr> <td class="left"> <div style="position: absolute; left: 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/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809967" href="?#comment-809967" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809965" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809967" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809967"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the detailed answer!</p></div> </div> </div> <div class="reply info"> <a class="comment-809967 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809967 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809967"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="810320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Anurag_20" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Anurag_20" title="Specialist Anurag_20" class="rated-user user-cyan">Anurag_20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/30/2021 19:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810320" href="?#comment-810320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810320" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1600346" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810320"> <div class="moveup"> <div class="ttypography"><p>O(n2) is also working for div2 C Great Graphs. <a href="https://codeforces.com/contest/1540/submission/120964787">https://codeforces.com/contest/1540/submission/120964787</a></p></div> </div> </div> <div class="reply info"> <a class="comment-810320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810320"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="813828" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/T404" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/T404" title="Master T404" class="rated-user user-orange">T404</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/09/2021 19:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-813828" href="?#comment-813828" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="813828" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="523287" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-813828"> <div class="moveup"> <div class="ttypography"><p>Div1D can be done in $$$O(n \sqrt{n})$$$. We can use square root decomposition to replace all BITs in tutorial. Since a value in a non-updated position changes by at most one and all values change in the same direction, the full recomputation is only needed in the updated position and we can perform an incremental change in $$$O(1)$$$ for values in each non-updated positions.</p><p><a href="https://codeforces.com/contest/1540/submission/121831547">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-813828 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-813828 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-813828"> <li> <div class="comment"> <table class="comment-table" commentId="834051" commentParentId="813828"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KeyID" style="position: relative;"> <img src='https://userpic.codeforces.org/226684/avatar/10e3671716bf6859.jpg'/> </a> <div><a href="/profile/KeyID" title="Grandmaster KeyID" class="rated-user user-red">KeyID</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/29/2021 12:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-834051" href="?#comment-834051" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-813828" style="font-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="834051" 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="834051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="226684" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-834051"> <div class="moveup"> <div class="ttypography"><p>Realy impressive solution. I'm surprised no stars were given to you until me. Maybe many people didn't get your idea since the solution is actually much more complicated than your brief comment(at least in my opinion). I also wrote a piece of code which used your method but simplified a small part of steps. <a href="https://codeforces.com/contest/1540/submission/127317031">Here</a> it is.</p></div> </div> </div> <div class="reply info"> <a class="comment-834051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-834051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-834051"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="837924" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Harolinch" style="position: relative;"> <img src='https://userpic.codeforces.org/427341/avatar/cf8608aeb55edc95.jpg'/> </a> <div><a href="/profile/Harolinch" title="Pupil Harolinch" class="rated-user user-green">Harolinch</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837924" href="?#comment-837924" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837924" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="427341" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837924"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a> in problem Tree array you said that Fixing a given root r, the expected value of the entire process is obviously the sum of the expected values for a fixed root divided by n.</p><p>why we divide by n at the end ? </p></div> </div> </div> <div class="reply info"> <a class="comment-837924 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837924 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837924"> <li> <div class="comment"> <table class="comment-table" commentId="837928" commentParentId="837924"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837928" href="?#comment-837928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-837924" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837928" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837928"> <div class="moveup"> <div class="ttypography"><p>The calculation is independent based on whichever node that you choose first (it becomes the “root”). Initially you choose one of $$$n$$$ nodes with equal probability so you divide by $$$n$$$ at the end after you’ve summed up the independent expected value after choosing the node $$$i$$$ initially.</p></div> </div> </div> <div class="reply info"> <a class="comment-837928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837928"> </ul> </div> </li> </ul> </div> <br/> <div id="editBox-100805" 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 firstPreview100805 = true; var lastPreviewContent100805 = ''; 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=100805] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=100805] 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-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, 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:33:28</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:'81289372dffb0c4e',t:'MTY5NjcwNzIwOC45MzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1540B
1540
B
ru
B. Древесный массив
<div class="problem-statement"><div class="header"><div class="title">B. Древесный массив</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задано дерево, состоящее из $$$n$$$ вершин. По заданному дереву вы строите массив, отмечая вершины по одной.</p><p>Первоначально, когда еще не помечено ни одной вершины, вы выбираете вершину равновероятно по всем вершинам дерева и отмечаете ее.</p><p>После этого, пока еще остаются непомеченные вершины, вы выбираете и помечаете вершину равновероятно среди всех еще непомеченных, но связанных по ребру хотя бы с одной помеченной вершиной.</p><p>Можно доказать, что данный процесс пометит все вершины в дереве.</p><p>Финальный массив $$$a$$$ — это список номеров вершин в порядке, в котором они были помечены.</p><p>Определите математическое ожидание количества инверсий в массиве, полученном на основе заданного дереве с помощью описанного выше алгоритма.</p><p>Количество инверсий в массиве $$$a$$$ — это количество пар индексов $$$(i, j)$$$ таких, что $$$i &lt; j$$$ и $$$a_i &gt; a_j$$$. Например, в массиве $$$[4, 1, 3, 2]$$$ количество инверсий равно $$$4$$$: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$2 \le n \le 200$$$) — количество вершин в дереве.</p><p>В следующих $$$n - 1$$$ строках заданы по два целых числа $$$x$$$ и $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), означающие ребро между вершинами $$$x$$$ и $$$y$$$.</p><p>Гарантируется, что заданные ребра образуют дерево.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите математическое ожидание количества инверсий в построенном массиве по модулю $$$10^9+7$$$.</p><p>Формально, пусть $$$M = 10^9+7$$$. Можно показать, что ответ может быть представлен в виде несократимой дроби $$$\frac{p}{q}$$$, где $$$p$$$ и $$$q$$$ — целые числа, и $$$q \not \equiv 0 \pmod{M}$$$. Выведите целое число, равное $$$p \cdot q^{-1} \bmod M$$$. Другими словами, выведите такое целое число $$$x$$$, что $$$0 \le x &lt; M$$$ и $$$x \cdot q \equiv p \pmod{M}$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 166666669 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 2 1 2 3 6 1 1 4 2 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 500000009 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 2 1 3 1 4 2 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 500000007 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Изображение дерева из первого примера:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/90dc1d034031a6ea1791910813d434e41e5d6432.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>В первом примере получающиеся массивы почти фиксированы. Если первоначально выбрана вершина $$$2$$$, то единственный возможный массив — это $$$[2, 1, 3]$$$ ($$$1$$$ инверсия). Если первоначально выбрана вершина $$$3$$$, то единственный возможный массив — это $$$[3, 1, 2]$$$ ($$$2$$$ инверсии). Если первоначально выбрана вершина $$$1$$$, то массивы $$$[1, 2, 3]$$$ ($$$0$$$ инверсий) и $$$[1, 3, 2]$$$ ($$$1$$$ инверсия) — это единственные варианты и они равновероятны. В результате математическое ожидание количества инверсий равно $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. </p><p>$$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, то есть ответ равен $$$166666669$$$.</p><p>Изображение дерева из второго примера: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/ef4aded5d5aff1ddebfd0e869167f44b63b678ac.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Изображение дерева из третьего примера: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/6ba27b979f5664e506fd0ae1d4c088000cac0fea.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="d7c0c6ac62ddcbd819c7727fdc62d149"/> <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="73d6e96a98bbd7625389194b3afaf471bd9b24fb"/> <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='d7c0c6ac62ddcbd819c7727fdc62d149'>&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%2F1540%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='d7c0c6ac62ddcbd819c7727fdc62d149'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1540">Codeforces Round 728 (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='d7c0c6ac62ddcbd819c7727fdc62d149'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1540/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Вероятности, мат. ожидания, случайные величины и др."> теория вероятностей </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *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='d7c0c6ac62ddcbd819c7727fdc62d149'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1027087"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d7c0c6ac62ddcbd819c7727fdc62d149'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1027087"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92093" title="Codeforces Round #728" target="_blank">Codeforces Round #728 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13928" resourceName="Codeforces Round #728" resourceManual="true" src="//codeforces.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/92199" title="Tutorial" target="_blank">Tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13942" 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/1540">Задачи</a></li> <li><a href="/contest/1540/submit">Отослать</a></li> <li><a href="/contest/1540/my">Мои посылки</a></li> <li><a href="/contest/1540/status">Статус</a></li> <li><a href="/contest/1540/hacks">Взломы</a></li> <li><a href="/contest/1540/room/1">Комната</a></li> <li><a href="/contest/1540/standings">Положение</a></li> <li><a href="/contest/1540/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_cab1a10d6323ee3d657d5c99d04690479fcd507b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Древесный массив</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задано дерево, состоящее из $$$n$$$ вершин. По заданному дереву вы строите массив, отмечая вершины по одной.</p><p>Первоначально, когда еще не помечено ни одной вершины, вы выбираете вершину равновероятно по всем вершинам дерева и отмечаете ее.</p><p>После этого, пока еще остаются непомеченные вершины, вы выбираете и помечаете вершину равновероятно среди всех еще непомеченных, но связанных по ребру хотя бы с одной помеченной вершиной.</p><p>Можно доказать, что данный процесс пометит все вершины в дереве.</p><p>Финальный массив $$$a$$$ — это список номеров вершин в порядке, в котором они были помечены.</p><p>Определите математическое ожидание количества инверсий в массиве, полученном на основе заданного дереве с помощью описанного выше алгоритма.</p><p>Количество инверсий в массиве $$$a$$$ — это количество пар индексов $$$(i, j)$$$ таких, что $$$i &lt; j$$$ и $$$a_i &gt; a_j$$$. Например, в массиве $$$[4, 1, 3, 2]$$$ количество инверсий равно $$$4$$$: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$2 \le n \le 200$$$) — количество вершин в дереве.</p><p>В следующих $$$n - 1$$$ строках заданы по два целых числа $$$x$$$ и $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), означающие ребро между вершинами $$$x$$$ и $$$y$$$.</p><p>Гарантируется, что заданные ребра образуют дерево.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите математическое ожидание количества инверсий в построенном массиве по модулю $$$10^9+7$$$.</p><p>Формально, пусть $$$M = 10^9+7$$$. Можно показать, что ответ может быть представлен в виде несократимой дроби $$$\frac{p}{q}$$$, где $$$p$$$ и $$$q$$$ — целые числа, и $$$q \not \equiv 0 \pmod{M}$$$. Выведите целое число, равное $$$p \cdot q^{-1} \bmod M$$$. Другими словами, выведите такое целое число $$$x$$$, что $$$0 \le x &lt; M$$$ и $$$x \cdot q \equiv p \pmod{M}$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 166666669 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 2 1 2 3 6 1 1 4 2 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 500000009 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 2 1 3 1 4 2 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 500000007 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Изображение дерева из первого примера:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/90dc1d034031a6ea1791910813d434e41e5d6432.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>В первом примере получающиеся массивы почти фиксированы. Если первоначально выбрана вершина $$$2$$$, то единственный возможный массив — это $$$[2, 1, 3]$$$ ($$$1$$$ инверсия). Если первоначально выбрана вершина $$$3$$$, то единственный возможный массив — это $$$[3, 1, 2]$$$ ($$$2$$$ инверсии). Если первоначально выбрана вершина $$$1$$$, то массивы $$$[1, 2, 3]$$$ ($$$0$$$ инверсий) и $$$[1, 3, 2]$$$ ($$$1$$$ инверсия) — это единственные варианты и они равновероятны. В результате математическое ожидание количества инверсий равно $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. </p><p>$$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, то есть ответ равен $$$166666669$$$.</p><p>Изображение дерева из второго примера: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/ef4aded5d5aff1ddebfd0e869167f44b63b678ac.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Изображение дерева из третьего примера: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/6ba27b979f5664e506fd0ae1d4c088000cac0fea.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c6c6cf9a161c',t:'MTY5NjY2NzM2Ny41OTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0412\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0438, \u043c\u0430\u0442. \u043e\u0436\u0438\u0434\u0430\u043d\u0438\u044f, \u0441\u043b\u0443\u0447\u0430\u0439\u043d\u044b\u0435 \u0432\u0435\u043b\u0438\u0447\u0438\u043d\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*2300"]
https://codeforces.com/blog/entry/92199
<!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="ea33d124a1ff874ace73f937748d303e"/> <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="Codeforces Round #728 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #728 Editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='ea33d124a1ff874ace73f937748d303e'>&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%2F92199">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='ea33d124a1ff874ace73f937748d303e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:31:32</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:31:32</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='ea33d124a1ff874ace73f937748d303e'/> <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/PurpleCrayon">PurpleCrayon</a></li> <li class="current selectedLava"><a href="/blog/PurpleCrayon">Blog</a></li> <li><a href="/teams/with/PurpleCrayon">Teams</a></li> <li><a href="/submissions/PurpleCrayon">Submissions</a></li> <li><a href="/groups/with/PurpleCrayon">Groups</a></li> <li><a href="/contests/with/PurpleCrayon">Contests</a></li> <li><a href="/contests/writer/PurpleCrayon">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/PurpleCrayon" style="text-decoration:none;color:black !important;">PurpleCrayon's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="92809"> <div class="title"> <a href="/blog/entry/92199"> <p>Codeforces Round #728 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a>, <a href="/topic/92809/en10">history</a>, <span class="format-humantime" title="Jun/25/2021 20:44">2 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><a href="/contest/1541/problem/A" title="Codeforces Round 728 (Div. 2)">1541A - Pretty Permutations</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The parity (whether $$$n$$$ is odd or even) matters.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Swapping two adjacent cats keeps both of them close to their original location and changes both of their locations.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>If $$$n$$$ is even, the optimal distance is $$$n$$$, and if $$$n$$$ is odd the optimal distance is $$$n+1$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541A">Tutorial is loading...</div></div></div><p><a href="/contest/1541/problem/B" title="Codeforces Round 728 (Div. 2)">1541B - Pleasant Pairs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>$$$i+j \leq 2 \cdot n$$$</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The number of pairs $$$(a, b)$$$ such that $$$a \cdot b \leq x$$$ is $$$O(x log x)$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/A" title="Codeforces Round 728 (Div. 1)">1540A - Great Graphs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What's the minimum value that an edge from $$$a$$$ to $$$b$$$ can be?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use edges with negative value whenever you can.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The sum of the values of edges with positive weight must be $$$\geq$$$ the maximum value in the array.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540A">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Tree Array</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Fix the initial node chosen and root the tree there, what is the contribution of each pair of nodes?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Nothing matters besides the path from node $$$a$$$ to node $$$b$$$, and the initially chosen node $$$r$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>You are given two stacks of size $$$a_1$$$ and $$$a_2$$$. In a single step, you randomly choose a stack to remove a single item from. What is the probability that $$$a_1$$$ becomes $$$0$$$ before $$$a_2$$$? Can you extend this argument for an arbitrary probability $$$p$$$ to remove from one of the two stacks, and a probability of $$$1-2p$$$ to do nothing?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/C2" title="Codeforces Round 728 (Div. 1)">1540C2 - Converging Array (Hard Version)</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What are the invariants? The monovariants?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What is the prefix sum array of the converged array? What is the difference array of the converged array?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you conducted the process on a prefix of size $$$1$$$, then of size $$$2$$$, and on and on?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How many values $$$x$$$ are actually interesting?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540C2">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Inverse Inversions</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The answer is always unique.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Try to figure out what the location of the $$$i$$$-th element would be if you only looked at the first $$$i$$$ elements, then the first $$$i+1$$$, etc. to find an $$$O(nq)$$$ solution.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use sqrt decomposition to optimize it.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540D">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/E" title="Codeforces Round 728 (Div. 1)">1540E - Tasty Dishes</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How much does each chef's initial dish contribute at time $$$k$$$?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you really, really wanted to use matrix exponentiation?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How can you multiply some vectors by a matrix in $$$O(N)$$$ time? (go back to linear algebra class)</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Decompose into linear combinations of eigenvectors.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540E">Tutorial is loading...</div></div></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/1540" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 1)</a> </span> </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/1541" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-191295-92809").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "191295", blogEntryId: "92199", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-92809"><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'>+96</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-92809"><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/PurpleCrayon"><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/PurpleCrayon"> PurpleCrayon </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="Jun/25/2021 20:44">2 years ago</span> </li> <li> <a href="/blog/entry/92199#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/92199#comments"> 170 </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="100805"> <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 (136)</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="808750" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808750" href="?#comment-808750" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808750" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-66" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-66</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808750"> <div class="moveup"> <div class="ttypography"><p>PURPLECRAYON ORZ</p></div> </div> </div> <div class="reply info"> <a class="comment-808750 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808750 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808750"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808751" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hbarp" style="position: relative;"> <img src='https://userpic.codeforces.org/1387715/avatar/c727a810db6ffb66.jpg'/> </a> <div><a href="/profile/hbarp" title="Candidate Master hbarp" class="rated-user user-violet">hbarp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808751" href="?#comment-808751" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808751" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="1387715" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-83</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808751"> <div class="moveup"> <div class="ttypography"><p>Damn, so orz round. <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Мастер PurpleCrayon">PurpleCrayon</a> orz</p></div> </div> </div> <div class="reply info"> <a class="comment-808751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808751"> <li> <div class="comment"> <table class="comment-table" commentId="808805" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/naman1601" style="position: relative;"> <img src='https://userpic.codeforces.org/1703219/avatar/d63fc523dc05fda8.jpg'/> </a> <div><a href="/profile/naman1601" title="Master naman1601" class="rated-user user-orange">naman1601</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808805" href="?#comment-808805" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808805" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-51" data-commentUserId="1703219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-51</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808805"> <div class="moveup"> <div class="ttypography"><p>yeah, amazing problemset, not speedforces at all :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808805 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808805 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808805"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808817" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LOVELY_BOY_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/LOVELY_BOY_" title="Newbie LOVELY_BOY_" class="rated-user user-gray">LOVELY_BOY_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808817" href="?#comment-808817" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-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="808817" 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="808817" class="CommentVoteFrame" data-commentRating="35" data-commentUserId="2089809" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808817"> <div class="moveup"> <div class="ttypography"><p>LOL <a class="rated-user user-blue" href="/profile/hbarp" title="Эксперт hbarp">hbarp</a>,even you didn't participate in the contest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808817 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808817 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808817"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808753" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DontLookBack" style="position: relative;"> <img src='https://userpic.codeforces.org/1534766/avatar/4eacdc5f9758fc28.jpg'/> </a> <div><a href="/profile/DontLookBack" title="Specialist DontLookBack" class="rated-user user-cyan">DontLookBack</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808753" href="?#comment-808753" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808753" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1534766" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808753"> <div class="moveup"> <div class="ttypography"><p>I am curious, how many div2 testers solved D?</p></div> </div> </div> <div class="reply info"> <a class="comment-808753 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808753 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808753"> <li> <div class="comment"> <table class="comment-table" commentId="808826" commentParentId="808753"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/highonjuice" style="position: relative;"> <img src='https://userpic.codeforces.org/1457566/avatar/f7988dd2af03d38b.jpg'/> </a> <div><a href="/profile/highonjuice" title="Pupil highonjuice" class="rated-user user-green">highonjuice</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808826" href="?#comment-808826" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808753" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808826" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1457566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808826"> <div class="moveup"> <div class="ttypography"><p>like 2 ppl, it was hard for me</p></div> </div> </div> <div class="reply info"> <a class="comment-808826 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808826 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808826"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808757" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tlatoani" style="position: relative;"> <img src='https://userpic.codeforces.org/614001/avatar/598b4e8358aad1b4.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/Tlatoani" title="Grandmaster Tlatoani" class="rated-user user-red">Tlatoani</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:18">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808757" href="?#comment-808757" style="font-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="808757" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="808757" class="CommentVoteFrame" data-commentRating="121" data-commentUserId="614001" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+121</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808757"> <div class="moveup"> <div class="ttypography"><h4>Alternate solution to <a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Инвертируем инверсии</a></h4><p>(Read the first nontrivial paragraph of the editorial before reading this alternate solution)</p><p>Let $$$p_r(k) = x$$$ denote that of the numbers $$$p(1), \ldots, p(r)$$$ in sorted order, $$$p(k)$$$ is equal to the $$$x$$$th of these numbers. We will take a decomposition strategy just as the editorial does, though our strategy will be different. We will divide $$$[1, n]$$$ into blocks of length $$$b$$$. For each block covering some interval $$$[l, r]$$$, we will store $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>This means that for any $$$k$$$, if we know $$$p_r(k)$$$ for some block $$$[l, r]$$$, then we can determine $$$p_{r'}(k)$$$ for the block $$$[l', r']$$$ immediately to the right by binary searching on the numbers stored for $$$[l', r']$$$. Therefore, we can perform queries in $$$O\left(\frac n b \lg b\right)$$$.</p><p>We now need to figure out updates. There are probably simple ways to perform updates in $$$O(b\lg b)$$$, but this yields an overall runtime of $$$O(q\sqrt n \lg n)$$$ which is too slow.</p><p>Therefore, we can instead store each block as a segment tree. For each range $$$[l, r]$$$ in the segment tree we store the same thing we store for the whole block: $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>We then have to quickly merge two intervals. We can merge two intervals of length $$$\lambda$$$ in $$$O(\lambda \lg \lambda)$$$ by doing binary search just as we did above, but this still only yields $$$O(b\lg b)$$$ update overall. However, these $$$\lambda$$$ binary searches can be optimized using two pointers to $$$O(\lambda)$$$, making the overall update $$$O(b)$$$.</p><p>We thus have $$$O\left(\frac n b \lg b\right)$$$ query and $$$O(b)$$$ update. Therefore, we can choose $$$b = \sqrt{n\lg n}$$$ to attain an overall runtime of $$$O\left(q\sqrt{n\lg n}\right)$$$ just as the editorial does.</p><p><a href="https://codeforces.com/contest/1540/submission/120611645">Submission in Kotlin</a></p><p><a href="https://codeforces.com/contest/1540/submission/120612729">Submission in C++</a></p><p>It is interesting to note that this solution is quite fast. At the time of writing this update, the C++ version is the fastest correct submission (and runs under 1 second!) and the Kotlin version is faster than the vast majority of submissions.</p></div> </div> </div> <div class="reply info"> <a class="comment-808757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808757"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808765" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardcode229" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardcode229" title="Newbie hardcode229" class="rated-user user-gray">hardcode229</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808765" href="?#comment-808765" style="font-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="808765" 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="808765" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1635180" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808765"> <div class="moveup"> <div class="ttypography"><p>The 3rd hint for the second problem is same as that of the first problem, is it related or a mistake? <strong>UPD:</strong> it is corrected.</p></div> </div> </div> <div class="reply info"> <a class="comment-808765 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808765 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808765"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808769" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/peanut" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/peanut" title="Specialist peanut" class="rated-user user-cyan">peanut</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:24">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808769" href="?#comment-808769" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808769" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="1167233" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+22</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808769"> <div class="moveup"> <div class="ttypography"><p>speedforces.</p></div> </div> </div> <div class="reply info"> <a class="comment-808769 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808769 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808769"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808781" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/graphs_11" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/graphs_11" title="Specialist graphs_11" class="rated-user user-cyan">graphs_11</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808781" href="?#comment-808781" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808781" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1610110" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808781"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">Problem B Detailed Explanation</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808781 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808781 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808781"> <li> <div class="comment"> <table class="comment-table" commentId="809069" commentParentId="808781"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:40">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809069" href="?#comment-809069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808781" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809069" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809069"> <div class="moveup"> <div class="ttypography"><p>Thank you, very well explained</p></div> </div> </div> <div class="reply info"> <a class="comment-809069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809069"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808790" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PC_E1052" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PC_E1052" title="Pupil PC_E1052" class="rated-user user-green">PC_E1052</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808790" href="?#comment-808790" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808790" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="811219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808790"> <div class="moveup"> <div class="ttypography"><p>c was too easy, d was too hard. but d was very nice problem though. </p></div> </div> </div> <div class="reply info"> <a class="comment-808790 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808790 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808790"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808793" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808793" href="?#comment-808793" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808793" class="CommentVoteFrame" data-commentRating="58" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+58</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808793"> <div class="moveup"> <div class="ttypography"><p>Paging <a class="rated-user user-legendary" href="/profile/ecnerwala" title="Легендарный гроссмейстер ecnerwala"><span class="legendary-user-first-letter">e</span>cnerwala</a> to explain his solution to D1E if he'd like. It seems offline?</p></div> </div> </div> <div class="reply info"> <a class="comment-808793 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808793 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808793"> <li> <div class="comment"> <table class="comment-table" commentId="808979" commentParentId="808793"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ecnerwala" 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/ecnerwala" title="Legendary Grandmaster ecnerwala" class="rated-user user-legendary"><span class="legendary-user-first-letter">e</span>cnerwala</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808979" href="?#comment-808979" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808793" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808979" class="CommentVoteFrame" data-commentRating="40" data-commentUserId="57502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808979"> <div class="moveup"> <div class="ttypography"><p>My solution is $$$O(K N^3 + QN)$$$. I just precomputed the coefficient of each $$$a_i$$$ for each prefix-range for each number of days since person $$$i$$$ becomes positive (only $$$1000$$$ possible days) in $$$O(N \cdot K \cdot N^2)$$$, and then summed up the appropriate ones to answer each query in $$$O(N)$$$. It's written in the offline style to use only $$$O(KN)$$$ memory at a time (grouped by $$$a_i$$$) instead of $$$O(KN^2)$$$.</p><p>My passing submission is just $$$KN^3 / 6$$$ instead of the $$$KN^3$$$ I submitted in contest :'(</p><p>If you guys wanted to prevent this, $$$K$$$ could've been much higher, like $$$1e18$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808979 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808979 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808979"> <li> <div class="comment"> <table class="comment-table" commentId="809002" commentParentId="808979"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809002" href="?#comment-809002" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808979" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809002" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809002"> <div class="moveup"> <div class="ttypography"><p>:( I knew of this solution (it’s why ML is tight) but I didn’t realize that it could be done offline with small memory. Of course $$$K$$$ higher is obvious solution but main issue is that the extra modulos from binary exponentiation make it very hard to pass in Java without allowing other unoptimal solutions through such as precomputing inverses of the matrix. Probably $$$k=10^5$$$ would’ve been a better choice. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-809002 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809002 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809002"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808795" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zukonit14" style="position: relative;"> <img src='https://userpic.codeforces.org/1192187/avatar/5afd49be87fb87d9.jpg'/> </a> <div><a href="/profile/zukonit14" title="Expert zukonit14" class="rated-user user-blue">zukonit14</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808795" href="?#comment-808795" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808795" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1192187" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808795"> <div class="moveup"> <div class="ttypography"><p>Does Div2 D deserved to be D Problem? According to me it should've been Div2 E.</p></div> </div> </div> <div class="reply info"> <a class="comment-808795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808795"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808796" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mangat_angad" style="position: relative;"> <img src='https://userpic.codeforces.org/1449578/avatar/d3cadb0c26e0c11f.jpg'/> </a> <div><a href="/profile/mangat_angad" title="Specialist mangat_angad" class="rated-user user-cyan">mangat_angad</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808796" href="?#comment-808796" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808796" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1449578" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808796"> <div class="moveup"> <div class="ttypography"><p>I feel like such an idiot for not being able to understand problem C (Div2). For some reason I thought the nodes were connected like this — 1-&gt;2-&gt;3-&gt;....-&gt;N and that we had to minimise answer by adding other edges (of negative weight in case they dont give a negative cycle) to this graph.</p></div> </div> </div> <div class="reply info"> <a class="comment-808796 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808796 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808796"> <li> <div class="comment"> <table class="comment-table" commentId="808896" commentParentId="808796"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808896" href="?#comment-808896" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808796" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808896" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808896"> <div class="moveup"> <div class="ttypography"><p>But that's exactly what I did, and the final answer is the sum of the array — sum of all subarrays. <a href="https://codeforces.com/contest/1541/submission/120611950">120611950</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808896 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808896 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808896"> <li> <div class="comment"> <table class="comment-table" commentId="808941" commentParentId="808896"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808941" href="?#comment-808941" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808896" style="font-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="808941" 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="808941" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808941"> <div class="moveup"> <div class="ttypography"><p>No, that's not what you did. To compute the answer via the method described above, you would have to compute how many elements are lesser than the current element at any given iteration and add them and also keep and their count using a Fenwick tree/ BIT. That's the incorrect approach though because sorting would be more optimal.</p></div> </div> </div> <div class="reply info"> <a class="comment-808941 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808941 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808941"> <li> <div class="comment"> <table class="comment-table" commentId="808952" commentParentId="808941"> <tr> <td class="left"> <div style="position: absolute; left: 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/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808952" href="?#comment-808952" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808941" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808952" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808952"> <div class="moveup"> <div class="ttypography"><p>Sorry if I misunderstood things. mangat_angad only mentioned adding negative weighed edges to the 1-&gt;2-&gt;3-&gt;...N graph, which is what I thought to arrive at my solution. The array I mentioned is indeed sorted and formed by distance differences which are the weights in the 1-&gt;2-&gt;3-&gt;...N graph. Unfortunately I'm still too noob to understand the tree structures you mentioned.</p></div> </div> </div> <div class="reply info"> <a class="comment-808952 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808952 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808952"> <li> <div class="comment"> <table class="comment-table" commentId="808955" commentParentId="808952"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808955" href="?#comment-808955" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808952" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808955" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808955"> <div class="moveup"> <div class="ttypography"><p>Nothing unfortunate about it, logic trumps everything </p></div> </div> </div> <div class="reply info"> <a class="comment-808955 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808955 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808955"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808797" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808797" href="?#comment-808797" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808797" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808797"> <div class="moveup"> <div class="ttypography"><p>Just want to apologize to authors for the stupidest question, I misread the task..</p></div> </div> </div> <div class="reply info"> <a class="comment-808797 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808797 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808797"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808813" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808813" href="?#comment-808813" style="font-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="808813" 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="808813" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808813"> <div class="moveup"> <div class="ttypography"><p>Can someone tell me the meaning of this line in problem Div2D/Div1B<br /></p> <blockquote><p>Note that, until reaching, l every possible process still has the same probability of reaching b before a. Therefore, we can assume that the process has reached l and calculate the probability from there.</p> </blockquote><p>What same probability are they talking about?</p></div> </div> </div> <div class="reply info"> <a class="comment-808813 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808813 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808813"> <li> <div class="comment"> <table class="comment-table" commentId="808831" commentParentId="808813"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808831" href="?#comment-808831" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808813" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808831" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808831"> <div class="moveup"> <div class="ttypography"><p>Here's what it's trying to say:</p><p>Suppose we start by marking the root. To mark a or b, we must first mark the lca, so we may assume that the lca has just been marked.</p></div> </div> </div> <div class="reply info"> <a class="comment-808831 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808831 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808831"> <li> <div class="comment"> <table class="comment-table" commentId="808840" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808840" href="?#comment-808840" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808840" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808840"> <div class="moveup"> <div class="ttypography"><p>And what does this line mean? <em>&quot;The problem can be rephrased as having two stacks of size dist(l,a) and dist(l,b) with an arbitrary p to remove a node from one of the two stack (and 1−2p to nothing) and finding the probability that dist(l,b) reaches zero before dist(l,a).&quot;</em></p></div> </div> </div> <div class="reply info"> <a class="comment-808840 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808840 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808840"> <li> <div class="comment"> <table class="comment-table" commentId="808857" commentParentId="808840"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808857" href="?#comment-808857" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808840" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808857" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808857"> <div class="moveup"> <div class="ttypography"><p>Once you've reached the lca $$$l$$$, in a single step you either step closer to $$$a$$$, step closer to $$$b$$$, or step closer to neither.</p></div> </div> </div> <div class="reply info"> <a class="comment-808857 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808857 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808857"> <li> <div class="comment"> <table class="comment-table" commentId="808862" commentParentId="808857"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808862" href="?#comment-808862" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808857" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808862" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808862"> <div class="moveup"> <div class="ttypography"><p>Can you add implementation for this problem please?</p></div> </div> </div> <div class="reply info"> <a class="comment-808862 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808862 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808862"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808849" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808849" href="?#comment-808849" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808849" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808849"> <div class="moveup"> <div class="ttypography"><p>So, we mark lca first (of course). But why wouldn't it affect the final probability of reaching b before a? I mean, why is it sufficient to calculate the probability after marking lca?</p></div> </div> </div> <div class="reply info"> <a class="comment-808849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808849"> <li> <div class="comment"> <table class="comment-table" commentId="808873" commentParentId="808849"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808873" href="?#comment-808873" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808849" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808873" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808873"> <div class="moveup"> <div class="ttypography"><p>Before marking the lca, there is no way to make more progress towards $$$b$$$ than $$$a$$$ or vice versa. The subset of marked vertices also does not change the probability of moving towards $$$a$$$ or $$$b$$$ after reaching the lca because we're choosing uniformly at random and exactly two vertices are of interest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808873 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808873 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808873"> <li> <div class="comment"> <table class="comment-table" commentId="808883" commentParentId="808873"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808883" href="?#comment-808883" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808873" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808883" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808883"> <div class="moveup"> <div class="ttypography"><p>Now I get it. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808883 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808883 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808883"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808814" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808814" href="?#comment-808814" style="font-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="808814" 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="808814" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808814"> <div class="moveup"> <div class="ttypography"><p>So, my Solution for <strong>Div1 Problem B</strong> / <strong>Div2 Problem D</strong> / <strong>1540B — Tree Array</strong>:</p><p>Chose two Nodes $$$A$$$ and $$$B$$$ with $$$A&gt;B$$$. </p><p><strong>First DFS:</strong> Find the path from $$$A$$$ to $$$B$$$. I call it $$$path_p$$$. On $$$path_p$$$ mark the distance to $$$B$$$ for each node. </p><p><strong>Second DFS:</strong> For each remaining node $$$N$$$ find the shortest path to $$$path_p$$$. It will hit it at some node of the $$$path_p$$$ which has some distance $$$D$$$ marked on it. We mark $$$N$$$ with $$$D$$$. (See comment below for image.)</p><p><strong>Calculation:</strong> For each node $$$N$$$ we can calculate $$$P_i$$$. $$$P_i$$$ is the probability to reach Node $$$B$$$ before we reach Node $$$A$$$. We sum $$$P_i$$$ for each node. $$$P_i$$$ is also the probability, that the pair of Nodes $$$A$$$ and $$$B$$$ with starting node $$$N$$$ will contribute to the inversion sum. </p><p><strong>Iteration:</strong> We need to repeat this for each pair $$$A$$$ and $$$B$$$. In the end we divide the answer by $$$n$$$, the amount of nodes (the probability to start with Node $$$N$$$). </p><p>This algorithm is $$$O(N^3)$$$. See my Solution <a href="/contest/1540/submission/120603369" title="Посылка 120603369 от OleschY">120603369</a></p> <div class="spoiler"><b class="spoiler-title">How to calculate P_i</b><div class="spoiler-content" style="display: none;"><p>I wrote myself a small helper DP-program to find the regularities. Let $$$D$$$ be the Distance between $$$A$$$ and $$$B$$$ and $$$d$$$ be the distance from the node $$$N$$$ to $$$B$$$. My educated guess was: $$$P_i=\frac{\sum_{i=0}^{d-1}\binom{D-1}{i} }{2^{D-1}}$$$</p> <div class="spoiler"><b class="spoiler-title">Helper Program</b><div class="spoiler-content" style="display: none;"><p>It checks for a path of some length for each Intervall $$$[A,B]$$$ which is already visited, what the probability to reach one node before the other is. </p> <pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; int solve(int n) { vector&lt;vector&lt;double&gt;&gt; dp(n, vector&lt;double&gt;(n, 0)); for(int i = 0; i &lt; n; ++i) { dp[0][i] = 1; dp[i][n - 1] = 0; } dp[0][n - 1] = -1; for(int w = n; w &gt;= 0; w--) { for(int i = 1; i + w &lt; n - 1; i++) { int l = i; int r = w + i; dp[l][r] = 0.5 * (dp[l - 1][r] + dp[l][r + 1]); } } cout &lt;&lt; n &lt;&lt; &quot;\n\n&quot;; for(int i = 0; i &lt; n; i++) { cout &lt;&lt; dp[i][i]*(1&lt;&lt;(n-2)) &lt;&lt; &quot;\n&quot;; } cout &lt;&lt; &quot;\n\n\n\n&quot;; return 0; } //====================== // Technical stuff //====================== int main() { int ntest = 12; for(int test = 2; test &lt; ntest; ++test) { solve(test); } return 0; } </code></pre></div></div></div></div></div> </div> </div> <div class="reply info"> <a class="comment-808814 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808814 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808814"> <li> <div class="comment"> <table class="comment-table" commentId="808843" commentParentId="808814"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808843" href="?#comment-808843" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808814" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808843" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808843"> <div class="moveup"> <div class="ttypography"><p>Can you explain your solution in a little bit more detail? :')</p></div> </div> </div> <div class="reply info"> <a class="comment-808843 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808843 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808843"> <li> <div class="comment"> <table class="comment-table" commentId="808869" commentParentId="808843"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808869" href="?#comment-808869" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808843" style="font-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="808869" 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="808869" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808869"> <div class="moveup"> <div class="ttypography"><p>Oof, I can give you an image, that shows how the distances from the two DFS are distributed on an example. You can see Nodes $$$A$$$ and $$$B$$$ and the numbers are the distances we write into the nodes. </p><p><img alt=" " src="/predownloaded/d8/2f/d82f98ecd2c1b4bd15b3c40e62476f6ae2741a64.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>If you have specific questions about some steps go ahead and ask. </p></div> </div> </div> <div class="reply info"> <a class="comment-808869 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808869 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808869"> <li> <div class="comment"> <table class="comment-table" commentId="810069" commentParentId="808869"> <tr> <td class="left"> <div style="position: absolute; left: 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/Mrajaryan" style="position: relative;"> <img src='https://userpic.codeforces.org/1377953/avatar/e904b3a3a2eac1ad.jpg'/> </a> <div><a href="/profile/Mrajaryan" title="Newbie Mrajaryan" class="rated-user user-gray">Mrajaryan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 15:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810069" href="?#comment-810069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808869" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810069" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1377953" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810069"> <div class="moveup"> <div class="ttypography"><p>what does the dp states mean in your helper program? I am unable to understand. Can you please explain?</p></div> </div> </div> <div class="reply info"> <a class="comment-810069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810069"> <li> <div class="comment"> <table class="comment-table" commentId="810097" commentParentId="810069"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 18:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810097" href="?#comment-810097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-810069" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810097"> <div class="moveup"> <div class="ttypography"><p>You have Nodes $$$1$$$ through $$$N$$$, neighbouring IDs are connected. The state $$$dp[l][r]$$$ is the probability, that node $$$N$$$ will be reached before node $$$1$$$ with all the nodes $$$l$$$ through $$$r$$$ marked already. Obviously $$$dp[1][x]=0$$$ and $$$dp[x][N]=1$$$ ($$$dp[1][N]$$$ can't happen). The recurrence is $$$dp[l][r]=(dp[l-1][r]+dp[l][r+1])/2$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-810097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808818" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808818" href="?#comment-808818" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808818" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808818"> <div class="moveup"> <div class="ttypography"><p>I can't grasp the editorial of Div 2 D/ Div 1 B. Can somebody provide a more intuitive explanation?</p></div> </div> </div> <div class="reply info"> <a class="comment-808818 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808818 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808818"> <li> <div class="comment"> <table class="comment-table" commentId="808821" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:45">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808821" href="?#comment-808821" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808821" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808821"> <div class="moveup"> <div class="ttypography"><p>same :(</p></div> </div> </div> <div class="reply info"> <a class="comment-808821 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808821 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808821"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808861" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808861" href="?#comment-808861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808861" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808861"> <div class="moveup"> <div class="ttypography"><p>Step 1. use linearity of expectation. The answer is</p> <center>$$$\sum_{a&lt;b} P(b\text{ appears before }a). $$$</center><p>Step 2: Observe that if we start by marking a vertex $$$c$$$ on the path between $$$a$$$ and $$$b$$$, and suppose the next marked vertex on the path is $$$d$$$. Then, the probability that $$$d$$$ is between $$$c$$$ and $$$a$$$ and the probability that $$$d$$$ is between $$$c$$$ and $$$b$$$ are both $$$1/2$$$. This is because there are only two choices for $$$d$$$ and we're choosing uniformly at random. This means that the answer only depends on $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p><p>Step 3: run a dp to calculate the probability that we mark $$$b$$$ before $$$a$$$ given $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808861"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808833" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808833" href="?#comment-808833" style="font-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="808833" 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="808833" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-72" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-72</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808833"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin &gt;&gt; t; while(t--){ int n; cin &gt;&gt; n; long long arr[n]; for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0; for(int i = 0; i &lt; n — 1; i++){ for(int j = arr[i] — 2 — i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } } } cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;; } return 0; }</p><p>/* Accepted code A different approach using arrays (as I don't know what vectors are, haven't read that) I hope this is a optimal approach. Any suggestions related to this are whole-heartedly welcomed. Also, please guide me how could I have optimized the code to a much extent. Thanks in advance! Keep programming! */</p></div> </div> </div> <div class="reply info"> <a class="comment-808833 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808833 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808833"> <li> <div class="comment"> <table class="comment-table" commentId="808844" commentParentId="808833"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808844" href="?#comment-808844" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808833" style="font-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="808844" 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="808844" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-35" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808844"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-808844 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808844 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808844"> <li> <div class="comment"> <table class="comment-table" commentId="808863" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808863" href="?#comment-808863" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808863" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808863"> <div class="moveup"> <div class="ttypography"><p>Not studied yet, I'm still a beginner, but planning to start soon. Thanks for the guidance.</p></div> </div> </div> <div class="reply info"> <a class="comment-808863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808863"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808879" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808879" href="?#comment-808879" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808879" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808879"> <div class="moveup"> <div class="ttypography"><p>once upon a time, I also did problems while not know what vectors are. sad times :'(</p></div> </div> </div> <div class="reply info"> <a class="comment-808879 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808879 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808879"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808926" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808926" href="?#comment-808926" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808926" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808926"> <div class="moveup"> <div class="ttypography"><p>There's no issue in not knowing vectors. Yes they are important I agree but not knowing vectors should not be discouraged. I became expert here without knowing anything about vectors plus he is a beginner so he shouldn't be discouraged like this.</p></div> </div> </div> <div class="reply info"> <a class="comment-808926 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808926 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808926"> <li> <div class="comment"> <table class="comment-table" commentId="808927" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Tech.Maniac" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Tech.Maniac" title="Expert Tech.Maniac" class="rated-user user-blue">Tech.Maniac</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808927" href="?#comment-808927" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808927" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1242860" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808927"> <div class="moveup"> <div class="ttypography"><p>+1, I agree with you. Same I was expert last year solely using arrays</p></div> </div> </div> <div class="reply info"> <a class="comment-808927 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808927 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808927"> <li> <div class="comment"> <table class="comment-table" commentId="809201" commentParentId="808927"> <tr> <td class="left"> <div style="position: absolute; left: 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/Yash.Amin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Yash.Amin" title="Specialist Yash.Amin" class="rated-user user-cyan">Yash.Amin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809201" href="?#comment-809201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808927" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809201" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-28" data-commentUserId="1226462" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-28</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809201"> <div class="moveup"> <div class="ttypography"><p>Bas kar bsdk kitna jhooth bolega</p></div> </div> </div> <div class="reply info"> <a class="comment-809201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809201"> <li> <div class="comment"> <table class="comment-table" commentId="809215" commentParentId="809201"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809215" href="?#comment-809215" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809215" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809215"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-blue" href="/profile/Yash.Amin" title="Эксперт Yash.Amin">Yash.Amin</a> Could you please refrain from using foul language on educational discussions. Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-809215 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809215 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809215"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808928" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808928" href="?#comment-808928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808928" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808928"> <div class="moveup"> <div class="ttypography"><p>Ah my bad, I did not want to come across as being arrogant, but I was genuinely confused that some people did not know vectors although they are using C++.</p></div> </div> </div> <div class="reply info"> <a class="comment-808928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808928"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808839" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamkiller04" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dreamkiller04" title="Newbie dreamkiller04" class="rated-user user-gray">dreamkiller04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808839" href="?#comment-808839" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2089608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808839"> <div class="moveup"> <div class="ttypography"><p>Please add implementations too.</p></div> </div> </div> <div class="reply info"> <a class="comment-808839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808839"> <li> <div class="comment"> <table class="comment-table" commentId="809106" commentParentId="808839"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809106" href="?#comment-809106" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808839" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809106" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809106"> <div class="moveup"> <div class="ttypography"><p>Simply running two loops and checking every case would give a TLE. So, we might want to minimize the number of operations. For this, we would only consider the cases where the sum of indices is a multiple of an element.</p><p>For this, we would first create two loops, one within the other, first loop iterating i from 0 to (n — 1) with an incrementation of 1. By observation, we can see that the first index for which the sum of indices will be a multiple of arr[i] is (arr[i] — 2 — i).</p><p>So, in the nested loop we will run j = (arr[i] — 2 — i) till (n — 1) with an incrementation of arr[i]. We would ignore the cases where j &lt; 0 or j &gt;= n.</p><p>Finally, we need to check for how many cases this holds (arr[i] * arr[j] = i + j + 2 and j &gt; i).</p><p>Suggestions are welcomed!</p></div> </div> </div> <div class="reply info"> <a class="comment-809106 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809106 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809106"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808842" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808842" href="?#comment-808842" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808842" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-64" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-64</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808842"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){</p><p>ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);</p><p>int t;</p><p>cin &gt;&gt; t;</p><p>while(t--){</p><p>int n;</p> <pre>cin &gt;&gt; n;</pre><p>long long arr[n];</p> <pre>for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0;</pre><p>for(int i = 0; i &lt; n — 1; i++){</p> <pre>for(int j = arr[i] &amp;mdash; 2 &amp;mdash; i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } }</pre><p>}</p><p>cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;;</p><p>}</p> <pre>return 0;</pre><p>}</p><p>/* Accepted code</p><p>A different approach using arrays (as I don't know what vectors are, haven't read that)</p><p>I hope this is a optimal approach.</p><p>Any suggestions related to this are whole-heartedly welcomed.</p><p>Also, please guide me how could I have optimized the code to a much extent.</p><p>Thanks in advance!</p><p>Keep programming! </p><p>*/</p></div> </div> </div> <div class="reply info"> <a class="comment-808842 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808842 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808842"> <li> <div class="comment"> <table class="comment-table" commentId="808851" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808851" href="?#comment-808851" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808851" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808851"> <div class="moveup"> <div class="ttypography"><p>Use spoilers for writing codes, please!</p></div> </div> </div> <div class="reply info"> <a class="comment-808851 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808851 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808851"> <li> <div class="comment"> <table class="comment-table" commentId="808870" commentParentId="808851"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808870" href="?#comment-808870" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808851" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808870" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808870"> <div class="moveup"> <div class="ttypography"><p>Actually, this is my first comment. Don't know much of this stuff as of now, but I'll surely take care of it the very next time.</p></div> </div> </div> <div class="reply info"> <a class="comment-808870 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808870 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808870"> <li> <div class="comment"> <table class="comment-table" commentId="809760" commentParentId="808870"> <tr> <td class="left"> <div style="position: absolute; left: 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/sus" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sus" title="Pupil sus" class="rated-user user-green">sus</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 05:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809760" href="?#comment-809760" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808870" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809760" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1749651" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809760"> <div class="moveup"> <div class="ttypography"><p>what problem is your code for</p></div> </div> </div> <div class="reply info"> <a class="comment-809760 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809760 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809760"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808884" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sevlll777" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sevlll777" title="Grandmaster sevlll777" class="rated-user user-red">sevlll777</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808884" href="?#comment-808884" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808884" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="839333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808884"> <div class="moveup"> <div class="ttypography"><p>NICE CODESTYLE!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-808884 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808884 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808884"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809084" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cj2021" style="position: relative;"> <img src='https://userpic.codeforces.org/1927237/avatar/b64ff59bd9dcf385.jpg'/> </a> <div><a href="/profile/cj2021" title="Newbie cj2021" class="rated-user user-gray">cj2021</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809084" href="?#comment-809084" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809084" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1927237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809084"> <div class="moveup"> <div class="ttypography"><p>What is &amp;mdash?</p><p>Just curious to know as haven't seen it before.</p></div> </div> </div> <div class="reply info"> <a class="comment-809084 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809084 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809084"> <li> <div class="comment"> <table class="comment-table" commentId="809097" commentParentId="809084"> <tr> <td class="left"> <div style="position: absolute; left: 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/klahsiv" style="position: relative;"> <img src='https://userpic.codeforces.org/1590145/avatar/1bf86ae3d48e55b.jpg'/> </a> <div><a href="/profile/klahsiv" title="Expert klahsiv" class="rated-user user-blue">klahsiv</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809097" href="?#comment-809097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809084" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590145" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809097"> <div class="moveup"> <div class="ttypography"><p>it is minus (-).</p></div> </div> </div> <div class="reply info"> <a class="comment-809097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808848" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/willy108" style="position: relative;"> <img src='https://userpic.codeforces.org/1439320/avatar/d7f79ed4e8b32e9a.jpg'/> </a> <div><a href="/profile/willy108" title="Master willy108" class="rated-user user-orange">willy108</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808848" href="?#comment-808848" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808848" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="1439320" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808848"> <div class="moveup"> <div class="ttypography"><p>Div2 B can also be done in O(NsqrtN). We know that for a given pair of indeces i+j &lt; 2n, so any pair that a[i] * a[j] &lt; 2n will have to have one of the two terms be &lt;= sqrt(n) (with some off by one errors of course). So the algorithm is to store an array of pairs [array value, index] and sort that array by the value. If the array value is &lt;= sqrt(2n) we can naively loop over the rest of the array in O(n) time and check (be careful about overcount), and if the value is &gt; sqrt(n), we can ignore it. This works since when a[i] * a[j] &lt; 2n one of a[i] or a[j] has to be &lt;= sqrt(2n) and as a result, every pair will be counted.</p></div> </div> </div> <div class="reply info"> <a class="comment-808848 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808848 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808848"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808860" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bcollet" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bcollet" title="Master bcollet" class="rated-user user-orange">bcollet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808860" href="?#comment-808860" style="font-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="808860" 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="808860" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="858059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808860"> <div class="moveup"> <div class="ttypography"><p>I don't understand in div1 C why it's prefix of b, in the case i=3 we have $$$a_1+a_2+a_3=f_1+f_1+b_1+f_1+b_1+b_2$$$ so $$$f_1=(ap_i-2b_1-b_2)$$$ I believe the general formula is something in the taste of $$$f_1=(ap_i-ibp_{i-1}+bpt_{i-1})/i$$$ where bpt_i=b_1+2b_2+...+ib_i, I think I miss something<br />Edit: corrected</p></div> </div> </div> <div class="reply info"> <a class="comment-808860 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808860 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808860"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808865" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ParsaS" style="position: relative;"> <img src='https://userpic.codeforces.org/1590150/avatar/dc2d8c002d2c5e1e.jpg'/> </a> <div><a href="/profile/ParsaS" title="Candidate Master ParsaS" class="rated-user user-violet">ParsaS</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808865" href="?#comment-808865" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808865" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590150" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808865"> <div class="moveup"> <div class="ttypography"><p>Nice problems. thanks for almost fast editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-808865 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808865 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808865"> <li> <div class="comment"> <table class="comment-table" commentId="808871" commentParentId="808865"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/E404_Not_Found" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/E404_Not_Found" title="Expert E404_Not_Found" class="rated-user user-blue">E404_Not_Found</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808871" href="?#comment-808871" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808865" style="font-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="808871" 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="808871" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1662858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808871"> <div class="moveup"> <div class="ttypography"><p>Yes thanks for fast editorial :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808871 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808871 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808871"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808890" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vikash_8090_b" style="position: relative;"> <img src='https://userpic.codeforces.org/1969032/avatar/a0f23c893ae54e74.jpg'/> </a> <div><a href="/profile/vikash_8090_b" title="Newbie vikash_8090_b" class="rated-user user-gray">vikash_8090_b</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808890" href="?#comment-808890" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808890" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="1969032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808890"> <div class="moveup"> <div class="ttypography"><p>is there anyone who can't even solve one question of today's contest ..</p></div> </div> </div> <div class="reply info"> <a class="comment-808890 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808890 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808890"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808892" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808892" href="?#comment-808892" style="font-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="808892" 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="808892" class="CommentVoteFrame" data-commentRating="-6" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808892"> <div class="moveup"> <div class="ttypography"><p>Deleted :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808892 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808892 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808892"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808918" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prituladima" style="position: relative;"> <img src='https://userpic.codeforces.org/116750/avatar/ca46d0256a294b26.jpg'/> </a> <div><a href="/profile/prituladima" title="Pupil prituladima" class="rated-user user-green">prituladima</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808918" href="?#comment-808918" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808918" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="116750" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808918"> <div class="moveup"> <div class="ttypography"><p>Please explain div2c/div1a problem a little bit more. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808918 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808918 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808918"> <li> <div class="comment"> <table class="comment-table" commentId="808921" commentParentId="808918"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808921" href="?#comment-808921" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808918" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808921" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808921"> <div class="moveup"> <div class="ttypography"><p>Try out this <a href="https://youtube.com/c/MagentaCobra">channel</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808921 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808921 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808921"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808950" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jakab922" style="position: relative;"> <img src='https://userpic.codeforces.org/53532/avatar/f9515e974f3ebcb1.jpg'/> </a> <div><a href="/profile/jakab922" title="Specialist jakab922" class="rated-user user-cyan">jakab922</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808950" href="?#comment-808950" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808950" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="53532" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808950"> <div class="moveup"> <div class="ttypography"><p>I don't really understand the need for a recursive function for the stack emptying probabilities in <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a>. I mean given that you have a stack of size <code>n</code> and and <code>m</code> you can basically have an array of size <code>n + m</code> filled with <code>0</code>s and <code>1</code>s where <code>0</code> at the <code>i</code>th place means that the <code>i</code>th element was taken from the first stack. Any such array which has <code>n</code> <code>0</code>s and <code>m</code> <code>1</code>s correspond to one process and it's easy to see that whoever takes the last spot in the array gets emptied later which gives an easy way to calculate the probabilities. Namely $$$\binom{n + m - 1}{n - 1} / \binom{n + m}{n}$$$ for the first and similar to the other. </p></div> </div> </div> <div class="reply info"> <a class="comment-808950 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808950 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808950"> <li> <div class="comment"> <table class="comment-table" commentId="808959" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cuom1999" style="position: relative;"> <img src='https://userpic.codeforces.org/253776/avatar/934152bc42a0b10c.jpg'/> </a> <div><a href="/profile/cuom1999" title="Grandmaster cuom1999" class="rated-user user-red">cuom1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808959" href="?#comment-808959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="253776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808959"> <div class="moveup"> <div class="ttypography"><p>If $$$m=2$$$ and $$$n=1$$$, your approach gives $$$\frac{1}{3}$$$. The correct answer should be $$$\frac{1}{4}$$$. </p><p>P/S: I'm also curious if there is any combinatoric approach for this,<a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808959"> <li> <div class="comment"> <table class="comment-table" commentId="809004" commentParentId="808959"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809004" href="?#comment-809004" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809004" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809004"> <div class="moveup"> <div class="ttypography"><p>I would guess that there’s no easy closed form. You can evaluate in $$$O(n)$$$ however by counting right up paths from $$$(a,0)$$$ to $$$(x,y)$$$ for all $$$a$$$ and multiplying by $$$2^{-steps}$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-809004 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809004 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809004"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809366" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/geekpradd" style="position: relative;"> <img src='https://userpic.codeforces.org/367430/avatar/427394aa7f5a63a0.jpg'/> </a> <div><a href="/profile/geekpradd" title="Candidate Master geekpradd" class="rated-user user-violet">geekpradd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809366" href="?#comment-809366" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809366" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="367430" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809366"> <div class="moveup"> <div class="ttypography"><p>The problem with this is that all the possibilities are not equilikely, consider $$$m=2, n=1$$$ and let $$$1$$$ denote entries from the stack of size $$$n$$$. Then the probability of obtaining $$$100$$$ is $$$1/2$$$, while obtaining $$$010$$$ and $$$001$$$ has a probability of $$$1/4$$$. Your approach assumes a uniform prior probability (in which case the answer is indeed $$$1/3$$$ whereas here it is $$$1/4$$$ which is the probability of getting $$$001$$$)</p></div> </div> </div> <div class="reply info"> <a class="comment-809366 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809366 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809366"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thunderboltz" style="position: relative;"> <img src='https://userpic.codeforces.org/1170396/avatar/4f017b259605bc5c.jpg'/> </a> <div><a href="/profile/thunderboltz" title="Newbie thunderboltz" class="rated-user user-gray">thunderboltz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808951" href="?#comment-808951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170396" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808951"> <div class="moveup"> <div class="ttypography"><p>Problem Div2C/Div1A, Plz somebody explain 3rd hint. I didn't get why this condition must be true </p><p><code>The sum of the values of edges with positive weight must be ≥ the maximum value in the array.</code></p></div> </div> </div> <div class="reply info"> <a class="comment-808951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808951"> <li> <div class="comment"> <table class="comment-table" commentId="808995" commentParentId="808951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808995" href="?#comment-808995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808995" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808995"> <div class="moveup"> <div class="ttypography"><p>I like to think about C this way: The cheapest node is the root, and the most expensive node, X, is the one with the highest value, D. Therefore no matter how we make our edges, we need at least 1 path from node to X with distance D. So let's build 1 single edge of positive weight from 1 to X with weight D.</p><p>Now from node X, all other nodes are &lt;= D. We can use negative edges to go there. Now the problem just becomes &quot;assign as many negative edges as possible&quot; to the rest of the nodes. </p></div> </div> </div> <div class="reply info"> <a class="comment-808995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808995"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808971" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808971" href="?#comment-808971" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808971" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808971"> <div class="moveup"> <div class="ttypography"><p>In problem <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a> I agree with everything up to:</p> <blockquote><p>Once l is reached, we now note that the probability that the process &quot;gets closer&quot; to b is always equal to the probability of getting closer to a.</p> </blockquote><p>I agree with this quote if it was about each individual set of marked nodes and single step for them. Because for any individual set of marked nodes, those probabilities is just one over the number of options at the moment. But I don't understand why I should forget about everything else what happens with other parts of tree, because after single step which is neither towards <strong>a</strong> neither towards <strong>b</strong>, the number of options (nodes we can mark on next step) may change.</p></div> </div> </div> <div class="reply info"> <a class="comment-808971 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808971 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808971"> <li> <div class="comment"> <table class="comment-table" commentId="809006" commentParentId="808971"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809006" href="?#comment-809006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808971" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809006" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809006"> <div class="moveup"> <div class="ttypography"><p>That is correct, but to see how it stays the same you can think of it inductively. Use strong induction and assume probability is the same no matter what the state of the tree is. Then from $$$(x,y)$$$ you always have an equal probability of ending up in one of the two states you can transition to because $$$p$$$ is always the same. Every scenario you enter one state, there’s another scenario with the same probability that enters the other state. So, the probability of entering one of the two states is the same as the other, thus $$$0.5$$$. Hopefully that makes things more clear.</p></div> </div> </div> <div class="reply info"> <a class="comment-809006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809006"> <li> <div class="comment"> <table class="comment-table" commentId="809113" commentParentId="809006"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809113" href="?#comment-809113" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809006" style="font-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="809113" 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="809113" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809113"> <div class="moveup"> <div class="ttypography"><p>Oh thanks, it's clear now. So, base of induction is when only <strong>l</strong> reached, and we can show that probability to make step towards <strong>a</strong> and <strong>b</strong> is same because for each individual set you can go from <strong>l</strong> to <strong>b</strong> instead of going from <strong>l</strong> into <strong>a</strong>, using exactly same steps in between (those steps which doesn't change distances to <strong>a</strong> and <strong>b</strong>). And similar holds for next steps.</p></div> </div> </div> <div class="reply info"> <a class="comment-809113 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809113 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809113"> <li> <div class="comment"> <table class="comment-table" commentId="821713" commentParentId="809113"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 08:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821713" href="?#comment-821713" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809113" style="font-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="821713" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="821713" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-821713"> <div class="moveup"> <div class="ttypography"><p>Can you explain this?</p><p>Assume $$$X$$$ is initially node we chose. Then define a function $$$g$$$ :</p><p>$$$g[a][b][STATE]$$$ = probability to reach a before b while state of the tree we reach is $$$STATE$$$, and $$$a$$$, $$$b$$$ is length of path.</p><p><img alt=" " src="/predownloaded/c2/32/c232d053fe3fbd1dedc06e56db58a7c139157987.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>follow the image, I can see : $$$g[a][b][STATE_x] = \frac{1}{4} (g[a][b][STATE_d] + g[a][b][STATE_e] + g[a — 1][b][closer_a] + g[a][b — 1][closer_b])$$$</p><p>It can easy see that the probability can change. Or I wrong in some where?</p></div> </div> </div> <div class="reply info"> <a class="comment-821713 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821713 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821713"> <li> <div class="comment"> <table class="comment-table" commentId="821861" commentParentId="821713"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 18:25">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821861" href="?#comment-821861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821713" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="821861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-821861"> <div class="moveup"> <div class="ttypography"><p>I'll hide my long explanation under spoiler</p> <div class="spoiler"><b class="spoiler-title">horrible wall of text</b><div class="spoiler-content" style="display: none;"><p>To put things into words, I want to define some things. First, suppose we marked some $$$s_1, s_2, s_3 ... s_k$$$ vertices in exact this order. Then, let $$$P(s)$$$ to be probability to mark them in this sequence. It can be decomposed into $$$P(s) = p_1 \cdot p_2 \cdot p_3 \cdot ... \cdot p_k$$$ where $$$p_i = 1/o_{i-1}$$$ where $$$o_i$$$ is number of options at step $$$i$$$ — number of opened vertices, except $$$p_0 = 1/n$$$, or $$$o_0 = n$$$.</p><p>Then, let $$$l = LCA(a, b)$$$ where $$$LCA$$$ is lowest common ancestor. Then, let $$$x_v$$$ to be some sort of 'cost'. For each $$$v$$$ on path between $$$a$$$ and $$$l$$$ it will be distance to $$$l$$$, and $$$-1$$$ everywhere else. Similarly, for each $$$v$$$ on path between $$$b$$$ and $$$l$$$ let $$$y_v$$$ to be distance to $$$l$$$ and $$$-1$$$ everywhere else. Let</p> <center>$$$ A(s) = \max\limits_{v\in s}x_v \\ B(s) = \max\limits_{v\in s}y_v $$$</center><p>Then $$$A(s)$$$ is equal to how far we reach $$$a$$$, and $$$B(s)$$$ is equal to how far we reach $$$b$$$. Let say we are in situation $$$(A(s), B(s))$$$ after marking $$$s$$$, and therefore situation is pair of numbers. Situation $$$(-1,-1)$$$ corresponds that no vertex is marked on path from $$$a$$$ to $$$b$$$. Situation $$$(0,0)$$$ corresponds to only $$$l$$$ marked on path from $$$a$$$ to $$$b$$$. And situation $$$(1,0)$$$ corresponds to $$$l$$$ and single vertex towards $$$a$$$ is marked.</p><p>Finally, let say sequence of marks $$$s$$$ reached state $$$(A(s), B(s))$$$ if either $$$A(s) = x_{s_k}$$$ or $$$B(s) = y_{s_k}$$$, in other words, last vertex is on path from $$$a$$$ to $$$b$$$ and it did change situation.</p><p>Now, what we want to prove is following:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha+1,\beta)} P(s) = \sum\limits_{s\;reached\;(\alpha,\beta+1)} P(s)$$$</center><p><strong>For some fixed</strong> $$$s_1$$$, which is root we chosen. And the way we prove it is that $$$s$$$ that is reached $$$(\alpha+1,\beta)$$$ consists of $$$u$$$ that reached $$$(\alpha,\beta)$$$ plus additional steps: $$$w$$$ plus $$$s_k$$$. So $$$s = u..w..s_k$$$ where $$$..$$$ is concatenation. It's easy to see what none of vertices from $$$w$$$ is on path from $$$a$$$ to $$$b$$$. Also, it's easy to see that we could instead of choosing $$$s_k$$$ could choose vertex $$$z$$$ towards $$$b$$$, and it would have same probability. In other words $$$P(s) = P(u..w..z)$$$. And this $$$u..w..z$$$ should reach state $$$(\alpha, \beta+1)$$$. So it should be in right side sum of our equation we want to prove.</p><p>So, for any $$$s$$$ from left sum, we can make $$$s'$$$ from right sum in unique way, and it will have same $$$P(s) = P(s')$$$. Similarly, for any $$$s$$$ from right sum, we can make $$$s'$$$ from left sum in unique way, and it will have same $$$P(s) = P(s')$$$. So this is bijection, and each element from left sum corresponds to element from right sum with same value, so those sums should have same value. Therefore it's equality.</p><p>Initially I wanted to trim $$$s$$$ from $$$(\alpha+1,\beta)$$$ to $$$(\alpha,\beta)$$$ and show similar thing based on following sum:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha,\beta)} P(s)$$$</center><p>Which is probability to reach state $$$(\alpha, \beta)$$$, but luckily it didn't required. I'll use notation $$$P(reach(\alpha, \beta))$$$ for this probability.</p><p>Thing that is not covered though: why this equality can be translated into probability $$$= 1/2$$$? Well, from $$$(\alpha, \beta)$$$ you eventually will reach either $$$(\alpha+1,\beta)$$$ or $$$(\alpha,\beta+1)$$$, so you can see this as example of Law of total probability. $$$P(reach(\alpha, \beta)) = P(reach (\alpha+1, \beta)) + P(reach (\alpha, \beta+1))$$$, because events $$$(\alpha+1,\beta)$$$ and $$$(\alpha,\beta+1)$$$ are disjoint events given $$$(\alpha, \beta)$$$ is reached. And we proved they have equal probability so $$$P(reach(\alpha, \beta)) = 2\cdot P(reach (\alpha+1, \beta))$$$, so $$$P(reach (\alpha+1, \beta)) = 1/2\cdot P(reach(\alpha, \beta))$$$ which we actually use.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-821861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821861"> <li> <div class="comment"> <table class="comment-table" commentId="822027" commentParentId="821861"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/28/2021 13:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822027" href="?#comment-822027" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821861" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="822027" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822027"> <div class="moveup"> <div class="ttypography"><p>Oh, sorry, there is one missing part. We proved $$$P(reached(\alpha+1,\beta))=P(reached(\alpha,\beta+1))$$$ <strong>given</strong> $$$(\alpha,\beta)$$$ is reached, but this is actually what we need. This <strong>given</strong> condition is what I missed. Without <strong>given</strong> we could reach $$$(\alpha+1,\beta)$$$ from reaching $$$(\alpha+1,\beta-1)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-822027 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822027 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822027"> <li> <div class="comment"> <table class="comment-table" commentId="822370" commentParentId="822027"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 13:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822370" href="?#comment-822370" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822027" style="font-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="822370" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="822370" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822370"> <div class="moveup"> <div class="ttypography"><p>Thanks for amz explain. I realize that I had some missunderstand in the way we calc $$$P(reach\ A\ before\ B)$$$</p><p>This's exactly what in my mind one day ago: let $$$s = ...a...b...$$$ where $$$a$$$ and $$$b$$$ is node $$$a$$$ and node $$$b$$$, &quot;$$$...$$$&quot; mean some node between them which we chose them in exactly that order, or in other word, $$$s$$$ is state represent what we chose (exact in this order) I think $$$P(reach\ A\ before\ B)$$$ (or $$$P(A&lt;B)$$$) must be calculate in this way :</p><p>$$$P(A&lt;B) = \sum_{\substack{all\ s\ which\ a&lt;b}} P(s)$$$</p><p>But unfortunately, it's wrong (may be, or I still missunderstanding)</p><p>$$$P(A) = \sum_{\substack{all\ B[i]\ \subseteq\ A}} P(B[i])$$$ if and only if all $$$B[i]$$$ are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-822370 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822370 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822370"> <li> <div class="comment"> <table class="comment-table" commentId="822755" commentParentId="822370"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 22:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822755" href="?#comment-822755" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822370" style="font-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="822755" 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="822755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822755"> <div class="moveup"> <div class="ttypography"><p>$$$P(A &lt; B)$$$ in your terms is exactly what we need (if a = A and b = B).</p><p>I don't understand last formula, everything else looks fine.</p><p>And to find $$$P(A &lt; B)$$$ we use fact above and calculate all possible ways to reach $$$a$$$ earlier than $$$b$$$ we use $$$(\alpha, \beta)$$$ states using my notation: you either get $$$\alpha$$$ equal to dist to $$$a$$$ when $$$\beta$$$ = 0, or $$$\beta$$$ = 1, or 2, or 3...</p> <center>$$$ P(A &lt; B) = \\ =\sum\limits_{i=0}^{dist(b,l)}P(reach(dist(a,l),i)\;given\; reached(dist(a,l)-1,i)) \\ = \sum\limits_{i=0}^{dist(b,l)}P(reached(dist(a,l)-1,i))\cdot \frac{1}{2} $$$</center><p>Or you can rephrase task into other task with two kind of balls. What probability to remove all balls of one kind earlier than other, if you pick one or other kind of ball with probability 1/2.</p></div> </div> </div> <div class="reply info"> <a class="comment-822755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822755"> </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="808983" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/xsc" style="position: relative;"> <img src='https://userpic.codeforces.org/343/avatar/9eaf243b1eb8c3d4.jpg'/> </a> <div><a href="/profile/xsc" title="Specialist xsc" class="rated-user user-cyan">xsc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808983" href="?#comment-808983" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808983" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="343" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808983"> <div class="moveup"> <div class="ttypography"><p>Div2 D, O(N^4) solution <a href="/contest/1541/submission/120623566" title="Посылка 120623566 от xsc">120623566</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808983 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808983 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808983"> <li> <div class="comment"> <table class="comment-table" commentId="809278" commentParentId="808983"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DavidXu_JJ" style="position: relative;"> <img src='https://userpic.codeforces.org/2003708/avatar/623dc8036b4e9d72.jpg'/> </a> <div><a href="/profile/DavidXu_JJ" title="Expert DavidXu_JJ" class="rated-user user-blue">DavidXu_JJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809278" href="?#comment-809278" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808983" style="font-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="809278" 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="809278" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2003708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809278"> <div class="moveup"> <div class="ttypography"><p>Your code really helps me a lot in debugging,thanks.</p><p>By the way,it's weired that I get Wrong6 when I try to optimize to O(N^3*logN) by binary search on tree.</p><p>I have tested my function on other online judge and my function seems to be correct.</p></div> </div> </div> <div class="reply info"> <a class="comment-809278 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809278 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809278"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809018" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ducati" style="position: relative;"> <img src='https://userpic.codeforces.org/699102/avatar/eff3c352646e914e.jpg'/> </a> <div><a href="/profile/ducati" title="Grandmaster ducati" class="rated-user user-red">ducati</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 03:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809018" href="?#comment-809018" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809018" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="699102" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809018"> <div class="moveup"> <div class="ttypography"><p>Although Div.2 D is harder than ever, in my opinion, it's such a useful and excellent problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-809018 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809018 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809018"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809046" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KanishkGoel" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/KanishkGoel" title="Expert KanishkGoel" class="rated-user user-blue">KanishkGoel</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809046" href="?#comment-809046" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809046" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1917239" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809046"> <div class="moveup"> <div class="ttypography"><p>Is it usual for people to post solutions online during the contest like this channel? <a href="https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ">https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809046 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809046 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809046"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809051" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809051" href="?#comment-809051" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809051"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain why this submission <a href="/contest/1541/submission/120562335" title="Посылка 120562335 от Karnania7201">120562335</a> is failing for Div2 B? It would be a great help.</p></div> </div> </div> <div class="reply info"> <a class="comment-809051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809051"> <li> <div class="comment"> <table class="comment-table" commentId="809076" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809076" href="?#comment-809076" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809076" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809076"> <div class="moveup"> <div class="ttypography"><p>Bro you did not included the condition that i and j should be different i.e (i != j) because it is given in question that no are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-809076 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809076 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809076"> <li> <div class="comment"> <table class="comment-table" commentId="809079" commentParentId="809076"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:08">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809079" href="?#comment-809079" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809076" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809079" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809079"> <div class="moveup"> <div class="ttypography"><p>I think its covered as I started j from i+1. I tried that explicitly too but it didn't work. I wrote the same idea in a different way and it worked but this kind of implementation is not working.</p></div> </div> </div> <div class="reply info"> <a class="comment-809079 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809079 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809079"> <li> <div class="comment"> <table class="comment-table" commentId="809082" commentParentId="809079"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809082" href="?#comment-809082" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809079" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809082" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809082"> <div class="moveup"> <div class="ttypography"><p>yeah, you are right, I run your code using vector instead of creating memeset it worked fine, i guess there is some problem in that. <a href="https://codeforces.com/contest/1541/submission/120633207">120633207</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809082 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809082 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809082"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809081" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_NICkk" style="position: relative;"> <img src='https://userpic.codeforces.org/1543175/avatar/6084dd87f2c1cad9.jpg'/> </a> <div><a href="/profile/_NICkk" title="Expert _NICkk" class="rated-user user-blue">_NICkk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809081" href="?#comment-809081" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809081" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1543175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809081"> <div class="moveup"> <div class="ttypography"><p>Only fault in your code is that you didn't used memset correctly </p><p>I just changed your memset with this &quot; memset(ind, 0, sizeof(ind)) &quot; and it worked perfectly fine</p></div> </div> </div> <div class="reply info"> <a class="comment-809081 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809081 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809081"> <li> <div class="comment"> <table class="comment-table" commentId="809091" commentParentId="809081"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:37">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809091" href="?#comment-809091" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809081" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809091" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809091"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot to both of you. I shouldn't have used it without properly knowing about it. </p></div> </div> </div> <div class="reply info"> <a class="comment-809091 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809091 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809091"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809064" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vrintle" style="position: relative;"> <img src='https://userpic.codeforces.org/1991777/avatar/24d9007095afbbb6.jpg'/> </a> <div><a href="/profile/vrintle" title="Master vrintle" class="rated-user user-orange">vrintle</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809064" href="?#comment-809064" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809064" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1991777" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809064"> <div class="moveup"> <div class="ttypography"><p>Instead of $$$a_i \cdot a_j \leq 2n$$$, we could also check $$$a_i \cdot a_j \leq i+n$$$ which is a bit faster ($$$ \sim 62ms$$$).</p></div> </div> </div> <div class="reply info"> <a class="comment-809064 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809064 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809064"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809066" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809066" href="?#comment-809066" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809066" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809066"> <div class="moveup"> <div class="ttypography"><p>can anyone explain B. pleasant pairs more easy words?? </p></div> </div> </div> <div class="reply info"> <a class="comment-809066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809066"> <li> <div class="comment"> <table class="comment-table" commentId="809067" commentParentId="809066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809067" href="?#comment-809067" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809067" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809067"> <div class="moveup"> <div class="ttypography"><p>And also what is ask in 3rd question i cant understand what asked in it</p></div> </div> </div> <div class="reply info"> <a class="comment-809067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809067"> <li> <div class="comment"> <table class="comment-table" commentId="809070" commentParentId="809067"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809070" href="?#comment-809070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809067" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809070"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">https://www.youtube.com/watch?v=xCj_ZR5kENo</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809098" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809098" href="?#comment-809098" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809098" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809098"> <div class="moveup"> <div class="ttypography"><p>For those who are searching for a simple solution for great Graphs problems in O (nlogn). <a href="https://codeforces.com/contest/1541/submission/120600816">https://codeforces.com/contest/1541/submission/120600816</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809098 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809098 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809098"> <li> <div class="comment"> <table class="comment-table" commentId="809119" commentParentId="809098"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fjvzr" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/fjvzr" title="Newbie fjvzr" class="rated-user user-gray">fjvzr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809119" href="?#comment-809119" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809098" style="font-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="809119" 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="809119" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1623986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809119"> <div class="moveup"> <div class="ttypography"><p>Bro can u explain this soln????? i thought of taking all pairs that give negative edges except for the adjacent pairs.... bt getting wrong ans in 3rd 4th test case.....</p><p>while(n&gt;2) { sum-=(n-2)*(llabs(a[j]-a[i])); n--; // n = size i++; // i = 0 j--; // j = n-1 } cout&lt;&lt;sum&lt;&lt;endl;</p><p><a href="https://codeforces.com/contest/1541/submission/120636509">mysoln</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809119 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809119 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809119"> <li> <div class="comment"> <table class="comment-table" commentId="809124" commentParentId="809119"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809124" href="?#comment-809124" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809119" style="font-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="809124" 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="809124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809124"> <div class="moveup"> <div class="ttypography"><p>My solution is simple. First sort the array. </p><p>Then start connecting adjacent values with their differences. This way sum of all edges with positive weight will be same as the sum of adjacent differences in the array.</p><p>After that start making negative edges for every i. So each i will have i negative edges. Where negative weight is same as -(arr[i] — arr[j]).</p><p>Instead of search it for every j I have formula as (prefixsum till i) — arr[i]*i</p></div> </div> </div> <div class="reply info"> <a class="comment-809124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809124"> <li> <div class="comment"> <table class="comment-table" commentId="809132" commentParentId="809124"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809132" href="?#comment-809132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809124" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809132"> <div class="moveup"> <div class="ttypography"><p>can you tell me why are we sorting the array for a particular node call it x we need to add a negative weight from x to 1 , x to 2 x to 3 till x to x-1 keeping in mind the the path sum doesn't become negative so why are we sorting the array</p></div> </div> </div> <div class="reply info"> <a class="comment-809132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809132"> <li> <div class="comment"> <table class="comment-table" commentId="809135" commentParentId="809132"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809135" href="?#comment-809135" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809135" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809135"> <div class="moveup"> <div class="ttypography"><p>We are sorting values only once so as to connect neighboring nodes with minimum values,i.e. difference b/w consecutive values.<br /> From this sum of positive edges will be minimum.</p></div> </div> </div> <div class="reply info"> <a class="comment-809135 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809135 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809135"> <li> <div class="comment"> <table class="comment-table" commentId="809139" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809139" href="?#comment-809139" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809139" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809139"> <div class="moveup"> <div class="ttypography"><p>ohhh thanks I got it</p></div> </div> </div> <div class="reply info"> <a class="comment-809139 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809139 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809139"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809145" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809145" href="?#comment-809145" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809145" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809145"> <div class="moveup"> <div class="ttypography"><p>My solution is working now I only needed to sort the array my code would have been accepted during the contest :(</p></div> </div> </div> <div class="reply info"> <a class="comment-809145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809145"> </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="809116" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ken_KaNeKi_997" style="position: relative;"> <img src='https://userpic.codeforces.org/1737228/avatar/50ceb845253df5d4.jpg'/> </a> <div><a href="/profile/Ken_KaNeKi_997" title="Newbie Ken_KaNeKi_997" class="rated-user user-gray">Ken_KaNeKi_997</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809116" href="?#comment-809116" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809116" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1737228" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809116"> <div class="moveup"> <div class="ttypography"><p>can anyone explain div2 B plz</p></div> </div> </div> <div class="reply info"> <a class="comment-809116 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809116 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809116"> <li> <div class="comment"> <table class="comment-table" commentId="809204" commentParentId="809116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809204" href="?#comment-809204" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809116" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809204" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809204"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/92199#comment-809178">here</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809204 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809204 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809204"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809122" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809122" href="?#comment-809122" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809122" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809122"> <div class="moveup"> <div class="ttypography"><p>Beautiful Problems. Amazing Round!!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-809122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809122"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809156" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dummybawa" style="position: relative;"> <img src='https://userpic.codeforces.org/1704408/avatar/1522f670cd21321.jpg'/> </a> <div><a href="/profile/dummybawa" title="Expert dummybawa" class="rated-user user-blue">dummybawa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809156" href="?#comment-809156" style="font-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="809156" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809156" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1704408" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809156"> <div class="moveup"> <div class="ttypography"><p>UPD: It's wrong. </p></div> </div> </div> <div class="reply info"> <a class="comment-809156 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809156 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809156"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809178" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809178" href="?#comment-809178" style="font-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="809178" 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="809178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809178"> <div class="moveup"> <div class="ttypography"><p>For DIV 2C/1A can anyone explain with this test case N = 6 and D = 0 1 2 3 2 3. What are the edges that we can have with their weights?</p></div> </div> </div> <div class="reply info"> <a class="comment-809178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809178"> <li> <div class="comment"> <table class="comment-table" commentId="809198" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Zemrith" style="position: relative;"> <img src='https://userpic.codeforces.org/1159882/avatar/2a6566e372882267.jpg'/> </a> <div><a href="/profile/Zemrith" title="Expert Zemrith" class="rated-user user-blue">Zemrith</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809198" href="?#comment-809198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-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="809198" 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="809198" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159882" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809198"> <div class="moveup"> <div class="ttypography"><p>Hello! The answer would be -18.</p><p>Diagram: <img alt=" " src="/predownloaded/8c/88/8c88a0230dea9f499896ee59def659611c605976.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Notice that once you sort the distances, the adjacent nodes have no effect on your final answer. But you can add negative edges as long as they are not adjacent, resulting in such a diagram. Hence you can use prefix sums to solve the problem. (if x nodes came before this, for each node, the answer to add is (x-1)*curr value — csum of first (x-1) nodes). </p><p>Hope that made sense!</p></div> </div> </div> <div class="reply info"> <a class="comment-809198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809198"> <li> <div class="comment"> <table class="comment-table" commentId="809218" commentParentId="809198"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:27">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809218" href="?#comment-809218" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809218" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809218"> <div class="moveup"> <div class="ttypography"><p>Thank you <a class="rated-user user-cyan" href="/profile/Zemrith" title="Специалист Zemrith">Zemrith</a> for so much detail explanation and the solution too it helped me a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-809218 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809218 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809218"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809199" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809199" href="?#comment-809199" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809199" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809199"> <div class="moveup"> <div class="ttypography"><p>first sort the array they will from non negative weight edges. 0 -&gt; 1 -&gt; 2 -&gt; 2 -&gt; 3 -&gt; 3 so the non negative weights will be 1 | 1 | 0 | 1 | 0. form here greedily build most negative weights(backward edges) such that there are no negative cycles.</p></div> </div> </div> <div class="reply info"> <a class="comment-809199 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809199 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809199"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809203" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809203" href="?#comment-809203" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809203" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809203"> <div class="moveup"> <div class="ttypography"><p>First you can sort D and get: <code> N = 6, D = [0, 1, 2, 2, 3, 3] </code></p><p>Now calculate the diffs:</p><p><code>diffs = [1, 1, 0, 1, 0]</code></p><p>The edges for this graph could be something like this:</p> <pre><code> 1 1 0 1 0 &lt;- forward edges 1 &lt;-&gt; 2 &lt;-&gt; 3 &lt;-&gt; 4 &lt;-&gt; 5 &lt;-&gt; 6 -1 -1 0 -1 0 &lt;- backward edges </code></pre><p>Now you have to add more negatives edges, and you could do this by choosing some <code>i</code> and <code>j</code>, <code>i &lt; j</code> and add an edges from <code>j</code> to <code>i</code>, and the weight will be sum of the values from <code>diff[i]</code> to <code>diff[j]</code>.</p><p>Another way to think about this is: look at <code>D</code> array, it represents distances between adjacent nodes, all we have to do is add all of the edges with length 2, then all of the edges of length 3, ..., all of the edges of length <code>N - 1</code>.</p><p>So, for our case we would have these edges</p> <pre><code>a b W ------- 1 2 - 1 2 3 - 1 3 4 - 0 &lt;- adjacent forward edges 4 5 - 1 5 6 - 0 2 1 - -1 3 2 - -1 4 3 - 0 &lt;- adjacent backward edges 5 4 - -1 6 5 - 0 3 1 - -2 4 2 - -1 5 3 - -1 &lt;- edges of length 2 6 4 - -1 4 1 - -2 5 2 - -2 &lt;- edges of length 3 6 3 - -1 5 1 - -3 6 2 - -2 &lt;- edges of length 4 6 1 - -3 &lt;- edges of length 5 </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809203 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809203 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809203"> <li> <div class="comment"> <table class="comment-table" commentId="809221" commentParentId="809203"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809221" href="?#comment-809221" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809203" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809221" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809221"> <div class="moveup"> <div class="ttypography"><p>Thank You <a class="rated-user user-green" href="/profile/ilidar" title="Ученик ilidar">ilidar</a> for clearing my doubt and for detailed explaination.</p></div> </div> </div> <div class="reply info"> <a class="comment-809221 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809221 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809221"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809280" href="?#comment-809280" style="font-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="809280" revisionCount="7" revision="7"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">7</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809280" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+18</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809280"> <div class="moveup"> <div class="ttypography"><p>Could someone please provide a more strict intuition or insight of Div2D/Div1B of why &quot;the actual probability p does not matter&quot;? The intuition in the editorial is still alien to me of why those choices of not progess toward to either stacks (and probability 'p' also changes from time to time too) doesn't matter.</p><p>Update: Here is the intuition I came up with (The strict proof can be found in the comment of the author below)</p><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left) in some states of the current tree.</p><p>now, we will try break this $$$dp_{i,j}$$$ down into the sum of $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$</p><p>We will try to illustrate this with trying to split and color, either red or blue, a stick of length $$$1$$$. The length of the sticks representing the 'probability', and the color of the sticks will represent $$$dp_{i-1,j}$$$(red) or $$$dp_{i,j-1}$$$(blue), depending on the color.</p><p>Suppose in the current state, we have probability $$$p$$$ for choosing to pop each stacks, and the rest $$$1-2p$$$ of doing nothing. The picture will look like this:</p><p><a href="https://ibb.co/q9HjQTm"><img alt="Tree-Array-Rep" border="0" src="/predownloaded/13/57/135732d2b0967af0f76c1dba28df72086f234c7d.png" style="max-width: 100.0%;max-height: 100.0%;" /></a></p><p>We will split the stick equally(*) into several sticks of length $$$p$$$, and then color two of them red and blue. (* We can split it evenly because in the original problem, $$$p$$$ is in the form $$$\frac{1}{number\ of\ candidate\ unmark\ nodes}$$$ ) Now, the remaining sticks represent the state of $$$dp_{i,j}$$$ again (in some other state of the entire tree, so might be in some different $$$p$$$). That means we will split those sticks similary.</p><p>The key observations is:</p><p>1) We know that, in the original problem, if we keep picking nodes that aren't progressing toward the target nodes, we will run out of nodes eventually and finally choose the two nodes. That means, all the sticks will eventually colored into 'red' and 'blue'.</p><p>2) When we split a stick into several smaller equal length sticks, we will color two of them into red and blue. <strong>Those two sticks always have the same length</strong>. That means, the total length of blue sticks and the total length of red sticks will be equal in the end.</p><p>Analogically, that means, eventually, $$$dp_{i,j}$$$ will split into $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$ evenly, no matter $$$p$$$ might be or the state of tree of $$$dp_{i,j}$$$ might be. Therefore, $$$dp_{i,j} = \frac{1}{2} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-809280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809280"> <li> <div class="comment"> <table class="comment-table" commentId="809284" commentParentId="809280"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809284" href="?#comment-809284" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809280" style="font-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="809284" 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="809284" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809284"> <div class="moveup"> <div class="ttypography"><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left), with having arbitary probability $$$0 &lt; p \leq 0.5$$$ of chosing to pick the top of each stack (and $$$1-2p$$$ for doing nothing). Then</p><p>$$$dp_{i,j}=\int_{0}^{0.5} x \cdot (dp_{i-1,j}+dp_{i,j-1}) + (1-2x) \cdot dp_{i,j} \,dx$$$</p><p>Solving the equation, we get $$$dp_{i,j}=\frac{1}{6} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$ What is the mistake in this logic?</p></div> </div> </div> <div class="reply info"> <a class="comment-809284 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809284 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809284"> <li> <div class="comment"> <table class="comment-table" commentId="809399" commentParentId="809284"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809399" href="?#comment-809399" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809284" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809399" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809399"> <div class="moveup"> <div class="ttypography"><p>The biggest issue with this logic is that it's assuming $$$p$$$ is arbitrary chosen from a certain state. While $$$p$$$ can be anything in the world, it is always an exact number from a certain state, hence why an integral is wrong. </p><p>As a different type of intuition, you can think, &quot;is it more likely to reach $$$(i-1, j)$$$ than state $$$(i, j-1)$$$&quot;? and vice versa. For me at least, I don't see how it's possible for either of those questions to be true, so they should be equal.</p><p>If you're looking for a more rigorously correct $$$dp$$$, it would look something like this.</p> <div class="spoiler"><b class="spoiler-title">Proof</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp_{i, j, S}$$$ denote the probability of reaching some node $$$i$$$ distance away before some node $$$j$$$ distance away where $$$S$$$ is a representation of the entire state of of the process (not necessarily an integer). I think you already understood why we can assume the $$$lca$$$ is already reached. We aim to show that $$$S$$$ does not matter in our calculation. Assume inductively that $$$S$$$ does not matter. So, we can assume that states $$$(i-1, j)$$$ and states $$$(i, j-1)$$$ are irrelevant to $$$S$$$. Hence, the part we need to care about is $$$(1-2p) dp_{i, j, S \rightarrow S_a}$$$. A way of thinking about this part of the transition is moving through the collection of $$$S$$$ with the state $$$(i, j)$$$. Obviously, the $$$dp$$$ is a $$$DAG$$$ because no state $$$S$$$ can reach another. Each bounce takes a certain probability $$$p$$$ which is just multiplied in the current path. So, for each state $$$S$$$ with state $$$(i, j)$$$, we have a certain probability to reach it by simply calculating $$$dp$$$ along a DAG as is traditional. Then, from those states of $$$(i, j)$$$ you transition to $$$(i, j-1)$$$ with an equal probability $$$(i-1, j)$$$. So, they have to be equal. Finally, this argument holds for any initial state $$$S$$$ that you reach, so we can conclude that, from any state $$$S$$$ with a state of $$$(i, j)$$$, the probability of transitions to $$$(i-1, j)$$$ and $$$(i, j-1)$$$ are always exactly $$$0.5$$$.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-809399 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809399 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809399"> <li> <div class="comment"> <table class="comment-table" commentId="809701" commentParentId="809399"> <tr> <td class="left"> <div style="position: absolute; left: 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/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809701" href="?#comment-809701" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809399" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809701" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809701"> <div class="moveup"> <div class="ttypography"><p>I see, thank you so much!</p></div> </div> </div> <div class="reply info"> <a class="comment-809701 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809701 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809701"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809298" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/satyam_singh93" style="position: relative;"> <img src='https://userpic.codeforces.org/1763011/avatar/9d9fa405de19ab0e.jpg'/> </a> <div><a href="/profile/satyam_singh93" title="Newbie satyam_singh93" class="rated-user user-gray">satyam_singh93</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809298" href="?#comment-809298" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809298" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1763011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809298"> <div class="moveup"> <div class="ttypography"><p>I am getting wrong ans . could someone tell me where the code make differene ( [yestrday competiton problem .</p><p>`](<a href="https://codeforces.com/contest/1541/problem/B)">https://codeforces.com/contest/1541/problem/B)</a>.</p> <pre><code>int main( ) { clock_t begin = clock(); file_i_o(); // Write your code here.... int t; cin&gt;&gt;t; while(t-- ){ int n; cin&gt;&gt;n; vector&lt;pair&lt;int,int&gt;&gt;v; v.push_back({0,0}); loop(i,0,n) { int x; cin&gt;&gt;x; v.pb({x,i+1}); } sort(v.begin()+1,v.end()); int count =0; for(int i=1 ; i&lt;=n;i++) { for(ll j=i+1;j&lt;=n;j++) { ll left = v[i].first * v[j].first; ll right = v[i].second + v[j].second; if(left == right) count++; if(left &gt; 2*n ) break; } } cout&lt;&lt;count&lt;&lt;endl; } </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809298 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809298 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809298"> <li> <div class="comment"> <table class="comment-table" commentId="809305" commentParentId="809298"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809305" href="?#comment-809305" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809298" style="font-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="809305" 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="809305" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809305"> <div class="moveup"> <div class="ttypography"><p>v[i].first * v[j].first can create overflow. So, you need to convert them to long long by using</p><p>ll left = 1LL * v[i].first * v[j].first;</p><p>instead and it would pass.</p><p>(Simply save the value in long long won't help. You need to convert them to long long before doing multiplication. 1LL* is one way)</p></div> </div> </div> <div class="reply info"> <a class="comment-809305 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809305 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809305"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809309" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809309" href="?#comment-809309" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809309" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809309"> <div class="moveup"> <div class="ttypography"><p>Hi, in problem Div1.B/Div2.D; I can't wrap my head around $$$F[x][y]=F[x−1][y]/2+F[x][y−1]/2$$$. Why is it not $$$F[x][y]=F[x−1][y+1]/2+F[x+1][y−1]/2$$$, can someone please explain to me why is my transition wrong and/or why is the aforementioned transition correct? </p></div> </div> </div> <div class="reply info"> <a class="comment-809309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809309"> <li> <div class="comment"> <table class="comment-table" commentId="809311" commentParentId="809309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809311" href="?#comment-809311" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809311" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809311"> <div class="moveup"> <div class="ttypography"><p>x and y is the distance left for each side right? So, if you take one out, it won't make sense to add that one to the other side since the distance should be either x-1 and y or x and y-1.</p></div> </div> </div> <div class="reply info"> <a class="comment-809311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809311"> <li> <div class="comment"> <table class="comment-table" commentId="809339" commentParentId="809311"> <tr> <td class="left"> <div style="position: absolute; left: 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/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809339" href="?#comment-809339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809339" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809339"> <div class="moveup"> <div class="ttypography"><p>Thank you so much I understand. I had a minor misunderstanding of the parameters to the dp state.</p></div> </div> </div> <div class="reply info"> <a class="comment-809339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809339"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809371" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:13">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809371" href="?#comment-809371" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809371" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809371"> <div class="moveup"> <div class="ttypography"><p>PLease explain why 2 same codes are not giving the same ans</p><p>code forces round 728 div2<br />Problem B :<a href="https://codeforces.com/contest/1541/problem/B">https://codeforces.com/contest/1541/problem/B</a></p><p>AC Submission : <a href="https://ide.codingblocks.com/s/579769">https://ide.codingblocks.com/s/579769</a></p><p>Wrong output Submission :<a href="https://ide.codingblocks.com/s/579771">https://ide.codingblocks.com/s/579771</a></p><p>Difference is using of macro (node) instead of pair&lt;int,int&gt; </p><p>Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-809371 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809371 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809371"> <li> <div class="comment"> <table class="comment-table" commentId="809379" commentParentId="809371"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809379" href="?#comment-809379" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809371" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809379" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809379"> <div class="moveup"> <div class="ttypography"><p>If i am using #define node pair&lt;int,int&gt; it is getting accepted but when i am using typedef pair&lt;int,int&gt; node; it is giving wrong answer</p><p>Why this is happening ?? Is it a bug??</p></div> </div> </div> <div class="reply info"> <a class="comment-809379 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809379 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809379"> <li> <div class="comment"> <table class="comment-table" commentId="809407" commentParentId="809379"> <tr> <td class="left"> <div style="position: absolute; left: 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/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 19:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809407" href="?#comment-809407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809379" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809407" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809407"> <div class="moveup"> <div class="ttypography"><p>Not really sure why this is happening.</p><p>However, I think the problem is the position of #define int long long. So, for #define pair&lt;int,int&gt; node it seems that compiler change node -&gt; pair&lt;int,int&gt; -&gt; pair&lt;long long, long long&gt;. However, when you do typedef, it still keeps in pair&lt;int, int&gt; which creates an overflow problem later on. </p><p>I did try moving #define int long long up above typedef and the code pass. So, my best guess is #define int long long only replace int after that position with long long. Thus, node is still pair&lt;int, int&gt; in the typedef solution, while node is changed to pair&lt;long long, long long&gt; in the second solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-809407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809407"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809627" href="?#comment-809627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809627"> <div class="moveup"> <div class="ttypography"><p>May I ask why in the Div1D solution ci=i-bi, I think it should be ci=bi ...</p></div> </div> </div> <div class="reply info"> <a class="comment-809627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809627"> <li> <div class="comment"> <table class="comment-table" commentId="809631" commentParentId="809627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809631" href="?#comment-809631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809631" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809631"> <div class="moveup"> <div class="ttypography"><p>Check the definition of bi again dude. bi here means <strong>number of elements greater than pi</strong>. So to get ci, which is <strong>number of elements smaller than pi</strong>, you need i-bi.</p></div> </div> </div> <div class="reply info"> <a class="comment-809631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809631"> <li> <div class="comment"> <table class="comment-table" commentId="809636" commentParentId="809631"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809636" href="?#comment-809636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809636"> <div class="moveup"> <div class="ttypography"><p>I read it again. If I read it correctly, bi stands for j&lt;i,pj&gt;pi, and ci stands for j&gt;i,pj&lt;pi. For example, p={1,3,5,4,6,2}, I think b4=1,c4=1, please point out my problem</p></div> </div> </div> <div class="reply info"> <a class="comment-809636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809636"> <li> <div class="comment"> <table class="comment-table" commentId="809638" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809638" href="?#comment-809638" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809638" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809638"> <div class="moveup"> <div class="ttypography"><p>oh, the array index starts from 1</p></div> </div> </div> <div class="reply info"> <a class="comment-809638 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809638 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809638"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809639" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809639" href="?#comment-809639" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809639" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809639"> <div class="moveup"> <div class="ttypography"><p>You are right.</p><p>I guess it might just be typo and ci stands for j&lt;i, pj&lt;pi. At least with this definition of ci the algorithm seems correct :)</p></div> </div> </div> <div class="reply info"> <a class="comment-809639 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809639 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809639"> <li> <div class="comment"> <table class="comment-table" commentId="809641" commentParentId="809639"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809641" href="?#comment-809641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809639" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809641"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-809641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809641"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809705" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/darthrevenge" style="position: relative;"> <img src='https://userpic.codeforces.org/1567000/avatar/ee31d2a91a9575b9.jpg'/> </a> <div><a href="/profile/darthrevenge" title="Candidate Master darthrevenge" class="rated-user user-violet">darthrevenge</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809705" href="?#comment-809705" style="font-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="809705" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809705" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1567000" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809705"> <div class="moveup"> <div class="ttypography"><p>Here's my solution of B div 1 / D div 2 without LCA, using single DFS per node. <a href="/contest/1540/submission/120700765" title="Посылка 120700765 от darthrevenge">120700765</a> It is similar to what <a class="rated-user user-violet" href="/profile/OleschY" title="Кандидат в мастера OleschY">OleschY</a> suggested above. I've tried to describe it in the <a href="https://codeforces.com/blog/entry/92284">blog</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-809705 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809705 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809705"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809951" href="?#comment-809951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809951"> <div class="moveup"> <div class="ttypography"><p>Can someone explain how you can find the LCA for each pair so quick? Iterating through every root is and then considering every pair is already N^3</p></div> </div> </div> <div class="reply info"> <a class="comment-809951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809951"> <li> <div class="comment"> <table class="comment-table" commentId="809965" commentParentId="809951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PurpleCrayon" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809965" href="?#comment-809965" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809965" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="1604355" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809965"> <div class="moveup"> <div class="ttypography"><p>There are a couple ways you could do it:</p> <ol> <li>Just use standard binary lifting (initialize once for each root). This runs in $$$\mathcal{O}(n^3 \log{}n)$$$, and should pass under the given constraints. You could also just use $$$\mathcal{O}(1)$$$ lca using an rmq over an euler tour.</li> <li>You could use a version of dp, where $$$dp[a][b] = lca(a, b)$$$. If the depth of $$$a$$$ is greater than the depth of $$$b$$$, $$$dp[a][b] = dp[parent[a]][b]$$$, otherwise $$$dp[a][b] = dp[a][parent[b]]$$$. The base cases are $$$dp[a][a] = a$$$ for all $$$a$$$. This runs in $$$\mathcal{O}(n^3)$$$.</li> <li>You could extend this idea and do the main solution's dp directly on the tree (without ever worrying about lca's). The recurrence is equivalent to the main solution ($$$dp[a][b] = \frac{dp[parent[a]][b]+dp[a][parent[b]]}{2}$$$ with the base cases being one node is an ancestor of the other.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-809965 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809965 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809965"> <li> <div class="comment"> <table class="comment-table" commentId="809967" commentParentId="809965"> <tr> <td class="left"> <div style="position: absolute; left: 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/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809967" href="?#comment-809967" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809965" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809967" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809967"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the detailed answer!</p></div> </div> </div> <div class="reply info"> <a class="comment-809967 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809967 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809967"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="810320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Anurag_20" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Anurag_20" title="Specialist Anurag_20" class="rated-user user-cyan">Anurag_20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/30/2021 19:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810320" href="?#comment-810320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810320" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1600346" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810320"> <div class="moveup"> <div class="ttypography"><p>O(n2) is also working for div2 C Great Graphs. <a href="https://codeforces.com/contest/1540/submission/120964787">https://codeforces.com/contest/1540/submission/120964787</a></p></div> </div> </div> <div class="reply info"> <a class="comment-810320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810320"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="813828" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/T404" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/T404" title="Master T404" class="rated-user user-orange">T404</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/09/2021 19:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-813828" href="?#comment-813828" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="813828" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="523287" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-813828"> <div class="moveup"> <div class="ttypography"><p>Div1D can be done in $$$O(n \sqrt{n})$$$. We can use square root decomposition to replace all BITs in tutorial. Since a value in a non-updated position changes by at most one and all values change in the same direction, the full recomputation is only needed in the updated position and we can perform an incremental change in $$$O(1)$$$ for values in each non-updated positions.</p><p><a href="https://codeforces.com/contest/1540/submission/121831547">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-813828 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-813828 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-813828"> <li> <div class="comment"> <table class="comment-table" commentId="834051" commentParentId="813828"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KeyID" style="position: relative;"> <img src='https://userpic.codeforces.org/226684/avatar/10e3671716bf6859.jpg'/> </a> <div><a href="/profile/KeyID" title="Grandmaster KeyID" class="rated-user user-red">KeyID</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/29/2021 12:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-834051" href="?#comment-834051" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-813828" style="font-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="834051" 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="834051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="226684" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-834051"> <div class="moveup"> <div class="ttypography"><p>Realy impressive solution. I'm surprised no stars were given to you until me. Maybe many people didn't get your idea since the solution is actually much more complicated than your brief comment(at least in my opinion). I also wrote a piece of code which used your method but simplified a small part of steps. <a href="https://codeforces.com/contest/1540/submission/127317031">Here</a> it is.</p></div> </div> </div> <div class="reply info"> <a class="comment-834051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-834051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-834051"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="837924" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Harolinch" style="position: relative;"> <img src='https://userpic.codeforces.org/427341/avatar/cf8608aeb55edc95.jpg'/> </a> <div><a href="/profile/Harolinch" title="Pupil Harolinch" class="rated-user user-green">Harolinch</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837924" href="?#comment-837924" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837924" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="427341" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837924"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a> in problem Tree array you said that Fixing a given root r, the expected value of the entire process is obviously the sum of the expected values for a fixed root divided by n.</p><p>why we divide by n at the end ? </p></div> </div> </div> <div class="reply info"> <a class="comment-837924 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837924 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837924"> <li> <div class="comment"> <table class="comment-table" commentId="837928" commentParentId="837924"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837928" href="?#comment-837928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-837924" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837928" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837928"> <div class="moveup"> <div class="ttypography"><p>The calculation is independent based on whichever node that you choose first (it becomes the “root”). Initially you choose one of $$$n$$$ nodes with equal probability so you divide by $$$n$$$ at the end after you’ve summed up the independent expected value after choosing the node $$$i$$$ initially.</p></div> </div> </div> <div class="reply info"> <a class="comment-837928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837928"> </ul> </div> </li> </ul> </div> <br/> <div id="editBox-100805" 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 firstPreview100805 = true; var lastPreviewContent100805 = ''; 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=100805] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=100805] 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-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, 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:33:28</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:'81289372dffb0c4e',t:'MTY5NjcwNzIwOC45MzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1540C1
1540
C1
ru
C1. Сходящийся массив (простая версия)
<div class="problem-statement"><div class="header"><div class="title">C1. Сходящийся массив (простая версия)</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-bf">Это — упрощенная версия задачи. Единственное различие в том, что в данной версии $$$q = 1$$$. Вы можете взламывать другие решения, только если решены обе версии задачи.</span></p><p>Рассмотрим процесс, проходящий на массивах $$$a$$$ и $$$b$$$ длины $$$n$$$ и $$$n-1$$$ соответственно. </p><p>Процесс — это бесконечная последовательность действий. Каждое действие имеет следующий вид: </p><ul> <li> Сначала выберем случайное целое число $$$i$$$ ($$$1 \le i \le n-1$$$). </li><li> Теперь одновременно присвоим $$$a_i = \min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right)$$$ и $$$a_{i+1} = \max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right)$$$ без округлений (то есть значения могут перестать быть целыми). </li></ul> Пример такой операции представлен в заметках.<p>Можно доказать, что массив $$$a$$$ сходится, т. е. для каждого $$$i$$$ существует предел, к которому $$$a_i$$$ сходится. Пусть функция $$$F(a, b)$$$ возвращает значение, к которому сходится $$$a_1$$$, в результате процесса на массивах $$$a$$$ и $$$b$$$.</p><p>Вам задан массив $$$b$$$, но не массив $$$a$$$. Однако вам задан третий массив $$$c$$$. Назовем массив $$$a$$$ хорошим, если он состоит из <span class="tex-font-style-bf">целых чисел</span> и удовлетворяет неравенству $$$0 \leq a_i \leq c_i$$$ для всех $$$1 \leq i \leq n$$$.</p><p>Ваша задача — посчитать количество хороших массивов $$$a$$$, для которых $$$F(a, b) \geq x$$$, для $$$q$$$ значений $$$x$$$. Так как ответ может быть слишком большим, выведите его по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$2 \le n \le 100$$$).</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$c_1, c_2 \ldots, c_n$$$ ($$$0 \le c_i \le 100$$$).</p><p>В третьей строке заданы $$$n-1$$$ целых чисел $$$b_1, b_2, \ldots, b_{n-1}$$$ ($$$0 \le b_i \le 100$$$).</p><p>В четвертой строке задано одно целое число $$$q$$$ ($$$q=1$$$).</p><p>В пятой строке заданы $$$q$$$ целых чисел $$$x_1, x_2, \ldots, x_q$$$ ($$$-10^5 \le x_i \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ целых чисел, где $$$i$$$-е число — ответ на $$$i$$$-й запрос, т. е. количество хороших массивов $$$a$$$ с $$$F(a, b) \geq x_i$$$ по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 3 4 2 1 1 -1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 56 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Объяснение далее предполагает, что $$$b = [2, 1]$$$ и $$$c=[2, 3, 4]$$$ (как в примере).</p><p>Примеры массивов $$$a$$$, которые <span class="tex-font-style-bf">не</span> являются хорошими: </p><ul> <li> $$$a = [3, 2, 3]$$$ не является хорошим, потому что $$$a_1 &gt; c_1$$$; </li><li> $$$a = [0, -1, 3]$$$ не является хорошим, потому что $$$a_2 &lt; 0$$$. </li></ul><p>Один из возможных хороших массивов $$$a$$$ — это $$$[0, 2, 4]$$$. Можно показать, что ни одна операция его не изменит, а потому $$$F(a, b) = a_1 = 0$$$.</p><p>Другой возможных хороший массив $$$a$$$ — это $$$[0, 1, 4]$$$. За одну операцию с $$$i = 1$$$ мы присваиваем $$$a_1 = \min(\frac{0+1-2}{2}, 0)$$$ и $$$a_2 = \max(\frac{0+1+2}{2}, 1)$$$. То есть, после одной операции с $$$i = 1$$$, $$$a$$$ становится равен $$$[-\frac{1}{2}, \frac{3}{2}, 4]$$$. Можно показать, что далее ни одна операция не изменит массив, а потому $$$F(a, b) = -\frac{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="28a2bbca554576e41e4a7bfdeb034af6"/> <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="Задача - C1 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="73d6e96a98bbd7625389194b3afaf471bd9b24fb"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - C1 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/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='28a2bbca554576e41e4a7bfdeb034af6'>&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%2F1540%2Fproblem%2FC1%3Flocale%3Dru">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='28a2bbca554576e41e4a7bfdeb034af6'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1540">Codeforces Round 728 (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='28a2bbca554576e41e4a7bfdeb034af6'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1540/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='28a2bbca554576e41e4a7bfdeb034af6'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1027088"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='28a2bbca554576e41e4a7bfdeb034af6'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1027088"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92093" title="Codeforces Round #728" target="_blank">Codeforces Round #728 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13928" resourceName="Codeforces Round #728" resourceManual="true" src="//codeforces.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/92199" title="Tutorial" target="_blank">Tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13942" 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/1540">Задачи</a></li> <li><a href="/contest/1540/submit">Отослать</a></li> <li><a href="/contest/1540/my">Мои посылки</a></li> <li><a href="/contest/1540/status">Статус</a></li> <li><a href="/contest/1540/hacks">Взломы</a></li> <li><a href="/contest/1540/room/1">Комната</a></li> <li><a href="/contest/1540/standings">Положение</a></li> <li><a href="/contest/1540/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { result.push(c); } } return result.join("").split("\n").map(value => value.trim()).join("\n"); }; </script> <div class="diff-popup"> </div> <div class="problemindexholder" problemindex="C1" data-uuid="ps_60af5de6a1f7cc799926dc3e252e059a804aacf2"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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">C1. Сходящийся массив (простая версия)</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-bf">Это — упрощенная версия задачи. Единственное различие в том, что в данной версии $$$q = 1$$$. Вы можете взламывать другие решения, только если решены обе версии задачи.</span></p><p>Рассмотрим процесс, проходящий на массивах $$$a$$$ и $$$b$$$ длины $$$n$$$ и $$$n-1$$$ соответственно. </p><p>Процесс — это бесконечная последовательность действий. Каждое действие имеет следующий вид: </p><ul> <li> Сначала выберем случайное целое число $$$i$$$ ($$$1 \le i \le n-1$$$). </li><li> Теперь одновременно присвоим $$$a_i = \min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right)$$$ и $$$a_{i+1} = \max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right)$$$ без округлений (то есть значения могут перестать быть целыми). </li></ul> Пример такой операции представлен в заметках.<p>Можно доказать, что массив $$$a$$$ сходится, т. е. для каждого $$$i$$$ существует предел, к которому $$$a_i$$$ сходится. Пусть функция $$$F(a, b)$$$ возвращает значение, к которому сходится $$$a_1$$$, в результате процесса на массивах $$$a$$$ и $$$b$$$.</p><p>Вам задан массив $$$b$$$, но не массив $$$a$$$. Однако вам задан третий массив $$$c$$$. Назовем массив $$$a$$$ хорошим, если он состоит из <span class="tex-font-style-bf">целых чисел</span> и удовлетворяет неравенству $$$0 \leq a_i \leq c_i$$$ для всех $$$1 \leq i \leq n$$$.</p><p>Ваша задача — посчитать количество хороших массивов $$$a$$$, для которых $$$F(a, b) \geq x$$$, для $$$q$$$ значений $$$x$$$. Так как ответ может быть слишком большим, выведите его по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$2 \le n \le 100$$$).</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$c_1, c_2 \ldots, c_n$$$ ($$$0 \le c_i \le 100$$$).</p><p>В третьей строке заданы $$$n-1$$$ целых чисел $$$b_1, b_2, \ldots, b_{n-1}$$$ ($$$0 \le b_i \le 100$$$).</p><p>В четвертой строке задано одно целое число $$$q$$$ ($$$q=1$$$).</p><p>В пятой строке заданы $$$q$$$ целых чисел $$$x_1, x_2, \ldots, x_q$$$ ($$$-10^5 \le x_i \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ целых чисел, где $$$i$$$-е число — ответ на $$$i$$$-й запрос, т. е. количество хороших массивов $$$a$$$ с $$$F(a, b) \geq x_i$$$ по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 3 4 2 1 1 -1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 56 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Объяснение далее предполагает, что $$$b = [2, 1]$$$ и $$$c=[2, 3, 4]$$$ (как в примере).</p><p>Примеры массивов $$$a$$$, которые <span class="tex-font-style-bf">не</span> являются хорошими: </p><ul> <li> $$$a = [3, 2, 3]$$$ не является хорошим, потому что $$$a_1 &gt; c_1$$$; </li><li> $$$a = [0, -1, 3]$$$ не является хорошим, потому что $$$a_2 &lt; 0$$$. </li></ul><p>Один из возможных хороших массивов $$$a$$$ — это $$$[0, 2, 4]$$$. Можно показать, что ни одна операция его не изменит, а потому $$$F(a, b) = a_1 = 0$$$.</p><p>Другой возможных хороший массив $$$a$$$ — это $$$[0, 1, 4]$$$. За одну операцию с $$$i = 1$$$ мы присваиваем $$$a_1 = \min(\frac{0+1-2}{2}, 0)$$$ и $$$a_2 = \max(\frac{0+1+2}{2}, 1)$$$. То есть, после одной операции с $$$i = 1$$$, $$$a$$$ становится равен $$$[-\frac{1}{2}, \frac{3}{2}, 4]$$$. Можно показать, что далее ни одна операция не изменит массив, а потому $$$F(a, b) = -\frac{1}{2}$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C1]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c6cf28909da8',t:'MTY5NjY2NzM2OC45NzcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*2700"]
https://codeforces.com/blog/entry/92199
<!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="ea33d124a1ff874ace73f937748d303e"/> <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="Codeforces Round #728 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #728 Editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='ea33d124a1ff874ace73f937748d303e'>&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%2F92199">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='ea33d124a1ff874ace73f937748d303e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:31:32</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:31:32</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='ea33d124a1ff874ace73f937748d303e'/> <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/PurpleCrayon">PurpleCrayon</a></li> <li class="current selectedLava"><a href="/blog/PurpleCrayon">Blog</a></li> <li><a href="/teams/with/PurpleCrayon">Teams</a></li> <li><a href="/submissions/PurpleCrayon">Submissions</a></li> <li><a href="/groups/with/PurpleCrayon">Groups</a></li> <li><a href="/contests/with/PurpleCrayon">Contests</a></li> <li><a href="/contests/writer/PurpleCrayon">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/PurpleCrayon" style="text-decoration:none;color:black !important;">PurpleCrayon's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="92809"> <div class="title"> <a href="/blog/entry/92199"> <p>Codeforces Round #728 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a>, <a href="/topic/92809/en10">history</a>, <span class="format-humantime" title="Jun/25/2021 20:44">2 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><a href="/contest/1541/problem/A" title="Codeforces Round 728 (Div. 2)">1541A - Pretty Permutations</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The parity (whether $$$n$$$ is odd or even) matters.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Swapping two adjacent cats keeps both of them close to their original location and changes both of their locations.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>If $$$n$$$ is even, the optimal distance is $$$n$$$, and if $$$n$$$ is odd the optimal distance is $$$n+1$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541A">Tutorial is loading...</div></div></div><p><a href="/contest/1541/problem/B" title="Codeforces Round 728 (Div. 2)">1541B - Pleasant Pairs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>$$$i+j \leq 2 \cdot n$$$</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The number of pairs $$$(a, b)$$$ such that $$$a \cdot b \leq x$$$ is $$$O(x log x)$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/A" title="Codeforces Round 728 (Div. 1)">1540A - Great Graphs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What's the minimum value that an edge from $$$a$$$ to $$$b$$$ can be?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use edges with negative value whenever you can.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The sum of the values of edges with positive weight must be $$$\geq$$$ the maximum value in the array.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540A">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Tree Array</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Fix the initial node chosen and root the tree there, what is the contribution of each pair of nodes?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Nothing matters besides the path from node $$$a$$$ to node $$$b$$$, and the initially chosen node $$$r$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>You are given two stacks of size $$$a_1$$$ and $$$a_2$$$. In a single step, you randomly choose a stack to remove a single item from. What is the probability that $$$a_1$$$ becomes $$$0$$$ before $$$a_2$$$? Can you extend this argument for an arbitrary probability $$$p$$$ to remove from one of the two stacks, and a probability of $$$1-2p$$$ to do nothing?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/C2" title="Codeforces Round 728 (Div. 1)">1540C2 - Converging Array (Hard Version)</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What are the invariants? The monovariants?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What is the prefix sum array of the converged array? What is the difference array of the converged array?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you conducted the process on a prefix of size $$$1$$$, then of size $$$2$$$, and on and on?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How many values $$$x$$$ are actually interesting?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540C2">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Inverse Inversions</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The answer is always unique.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Try to figure out what the location of the $$$i$$$-th element would be if you only looked at the first $$$i$$$ elements, then the first $$$i+1$$$, etc. to find an $$$O(nq)$$$ solution.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use sqrt decomposition to optimize it.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540D">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/E" title="Codeforces Round 728 (Div. 1)">1540E - Tasty Dishes</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How much does each chef's initial dish contribute at time $$$k$$$?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you really, really wanted to use matrix exponentiation?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How can you multiply some vectors by a matrix in $$$O(N)$$$ time? (go back to linear algebra class)</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Decompose into linear combinations of eigenvectors.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540E">Tutorial is loading...</div></div></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/1540" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 1)</a> </span> </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/1541" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-191295-92809").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "191295", blogEntryId: "92199", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-92809"><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'>+96</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-92809"><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/PurpleCrayon"><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/PurpleCrayon"> PurpleCrayon </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="Jun/25/2021 20:44">2 years ago</span> </li> <li> <a href="/blog/entry/92199#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/92199#comments"> 170 </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="100805"> <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 (136)</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="808750" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808750" href="?#comment-808750" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808750" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-66" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-66</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808750"> <div class="moveup"> <div class="ttypography"><p>PURPLECRAYON ORZ</p></div> </div> </div> <div class="reply info"> <a class="comment-808750 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808750 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808750"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808751" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hbarp" style="position: relative;"> <img src='https://userpic.codeforces.org/1387715/avatar/c727a810db6ffb66.jpg'/> </a> <div><a href="/profile/hbarp" title="Candidate Master hbarp" class="rated-user user-violet">hbarp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808751" href="?#comment-808751" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808751" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="1387715" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-83</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808751"> <div class="moveup"> <div class="ttypography"><p>Damn, so orz round. <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Мастер PurpleCrayon">PurpleCrayon</a> orz</p></div> </div> </div> <div class="reply info"> <a class="comment-808751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808751"> <li> <div class="comment"> <table class="comment-table" commentId="808805" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/naman1601" style="position: relative;"> <img src='https://userpic.codeforces.org/1703219/avatar/d63fc523dc05fda8.jpg'/> </a> <div><a href="/profile/naman1601" title="Master naman1601" class="rated-user user-orange">naman1601</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808805" href="?#comment-808805" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808805" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-51" data-commentUserId="1703219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-51</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808805"> <div class="moveup"> <div class="ttypography"><p>yeah, amazing problemset, not speedforces at all :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808805 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808805 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808805"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808817" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LOVELY_BOY_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/LOVELY_BOY_" title="Newbie LOVELY_BOY_" class="rated-user user-gray">LOVELY_BOY_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808817" href="?#comment-808817" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-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="808817" 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="808817" class="CommentVoteFrame" data-commentRating="35" data-commentUserId="2089809" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808817"> <div class="moveup"> <div class="ttypography"><p>LOL <a class="rated-user user-blue" href="/profile/hbarp" title="Эксперт hbarp">hbarp</a>,even you didn't participate in the contest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808817 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808817 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808817"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808753" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DontLookBack" style="position: relative;"> <img src='https://userpic.codeforces.org/1534766/avatar/4eacdc5f9758fc28.jpg'/> </a> <div><a href="/profile/DontLookBack" title="Specialist DontLookBack" class="rated-user user-cyan">DontLookBack</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808753" href="?#comment-808753" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808753" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1534766" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808753"> <div class="moveup"> <div class="ttypography"><p>I am curious, how many div2 testers solved D?</p></div> </div> </div> <div class="reply info"> <a class="comment-808753 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808753 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808753"> <li> <div class="comment"> <table class="comment-table" commentId="808826" commentParentId="808753"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/highonjuice" style="position: relative;"> <img src='https://userpic.codeforces.org/1457566/avatar/f7988dd2af03d38b.jpg'/> </a> <div><a href="/profile/highonjuice" title="Pupil highonjuice" class="rated-user user-green">highonjuice</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808826" href="?#comment-808826" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808753" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808826" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1457566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808826"> <div class="moveup"> <div class="ttypography"><p>like 2 ppl, it was hard for me</p></div> </div> </div> <div class="reply info"> <a class="comment-808826 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808826 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808826"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808757" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tlatoani" style="position: relative;"> <img src='https://userpic.codeforces.org/614001/avatar/598b4e8358aad1b4.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/Tlatoani" title="Grandmaster Tlatoani" class="rated-user user-red">Tlatoani</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:18">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808757" href="?#comment-808757" style="font-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="808757" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="808757" class="CommentVoteFrame" data-commentRating="121" data-commentUserId="614001" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+121</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808757"> <div class="moveup"> <div class="ttypography"><h4>Alternate solution to <a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Инвертируем инверсии</a></h4><p>(Read the first nontrivial paragraph of the editorial before reading this alternate solution)</p><p>Let $$$p_r(k) = x$$$ denote that of the numbers $$$p(1), \ldots, p(r)$$$ in sorted order, $$$p(k)$$$ is equal to the $$$x$$$th of these numbers. We will take a decomposition strategy just as the editorial does, though our strategy will be different. We will divide $$$[1, n]$$$ into blocks of length $$$b$$$. For each block covering some interval $$$[l, r]$$$, we will store $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>This means that for any $$$k$$$, if we know $$$p_r(k)$$$ for some block $$$[l, r]$$$, then we can determine $$$p_{r'}(k)$$$ for the block $$$[l', r']$$$ immediately to the right by binary searching on the numbers stored for $$$[l', r']$$$. Therefore, we can perform queries in $$$O\left(\frac n b \lg b\right)$$$.</p><p>We now need to figure out updates. There are probably simple ways to perform updates in $$$O(b\lg b)$$$, but this yields an overall runtime of $$$O(q\sqrt n \lg n)$$$ which is too slow.</p><p>Therefore, we can instead store each block as a segment tree. For each range $$$[l, r]$$$ in the segment tree we store the same thing we store for the whole block: $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>We then have to quickly merge two intervals. We can merge two intervals of length $$$\lambda$$$ in $$$O(\lambda \lg \lambda)$$$ by doing binary search just as we did above, but this still only yields $$$O(b\lg b)$$$ update overall. However, these $$$\lambda$$$ binary searches can be optimized using two pointers to $$$O(\lambda)$$$, making the overall update $$$O(b)$$$.</p><p>We thus have $$$O\left(\frac n b \lg b\right)$$$ query and $$$O(b)$$$ update. Therefore, we can choose $$$b = \sqrt{n\lg n}$$$ to attain an overall runtime of $$$O\left(q\sqrt{n\lg n}\right)$$$ just as the editorial does.</p><p><a href="https://codeforces.com/contest/1540/submission/120611645">Submission in Kotlin</a></p><p><a href="https://codeforces.com/contest/1540/submission/120612729">Submission in C++</a></p><p>It is interesting to note that this solution is quite fast. At the time of writing this update, the C++ version is the fastest correct submission (and runs under 1 second!) and the Kotlin version is faster than the vast majority of submissions.</p></div> </div> </div> <div class="reply info"> <a class="comment-808757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808757"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808765" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardcode229" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardcode229" title="Newbie hardcode229" class="rated-user user-gray">hardcode229</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808765" href="?#comment-808765" style="font-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="808765" 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="808765" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1635180" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808765"> <div class="moveup"> <div class="ttypography"><p>The 3rd hint for the second problem is same as that of the first problem, is it related or a mistake? <strong>UPD:</strong> it is corrected.</p></div> </div> </div> <div class="reply info"> <a class="comment-808765 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808765 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808765"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808769" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/peanut" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/peanut" title="Specialist peanut" class="rated-user user-cyan">peanut</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:24">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808769" href="?#comment-808769" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808769" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="1167233" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+22</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808769"> <div class="moveup"> <div class="ttypography"><p>speedforces.</p></div> </div> </div> <div class="reply info"> <a class="comment-808769 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808769 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808769"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808781" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/graphs_11" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/graphs_11" title="Specialist graphs_11" class="rated-user user-cyan">graphs_11</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808781" href="?#comment-808781" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808781" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1610110" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808781"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">Problem B Detailed Explanation</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808781 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808781 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808781"> <li> <div class="comment"> <table class="comment-table" commentId="809069" commentParentId="808781"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:40">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809069" href="?#comment-809069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808781" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809069" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809069"> <div class="moveup"> <div class="ttypography"><p>Thank you, very well explained</p></div> </div> </div> <div class="reply info"> <a class="comment-809069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809069"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808790" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PC_E1052" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PC_E1052" title="Pupil PC_E1052" class="rated-user user-green">PC_E1052</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808790" href="?#comment-808790" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808790" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="811219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808790"> <div class="moveup"> <div class="ttypography"><p>c was too easy, d was too hard. but d was very nice problem though. </p></div> </div> </div> <div class="reply info"> <a class="comment-808790 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808790 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808790"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808793" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808793" href="?#comment-808793" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808793" class="CommentVoteFrame" data-commentRating="58" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+58</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808793"> <div class="moveup"> <div class="ttypography"><p>Paging <a class="rated-user user-legendary" href="/profile/ecnerwala" title="Легендарный гроссмейстер ecnerwala"><span class="legendary-user-first-letter">e</span>cnerwala</a> to explain his solution to D1E if he'd like. It seems offline?</p></div> </div> </div> <div class="reply info"> <a class="comment-808793 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808793 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808793"> <li> <div class="comment"> <table class="comment-table" commentId="808979" commentParentId="808793"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ecnerwala" 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/ecnerwala" title="Legendary Grandmaster ecnerwala" class="rated-user user-legendary"><span class="legendary-user-first-letter">e</span>cnerwala</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808979" href="?#comment-808979" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808793" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808979" class="CommentVoteFrame" data-commentRating="40" data-commentUserId="57502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808979"> <div class="moveup"> <div class="ttypography"><p>My solution is $$$O(K N^3 + QN)$$$. I just precomputed the coefficient of each $$$a_i$$$ for each prefix-range for each number of days since person $$$i$$$ becomes positive (only $$$1000$$$ possible days) in $$$O(N \cdot K \cdot N^2)$$$, and then summed up the appropriate ones to answer each query in $$$O(N)$$$. It's written in the offline style to use only $$$O(KN)$$$ memory at a time (grouped by $$$a_i$$$) instead of $$$O(KN^2)$$$.</p><p>My passing submission is just $$$KN^3 / 6$$$ instead of the $$$KN^3$$$ I submitted in contest :'(</p><p>If you guys wanted to prevent this, $$$K$$$ could've been much higher, like $$$1e18$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808979 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808979 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808979"> <li> <div class="comment"> <table class="comment-table" commentId="809002" commentParentId="808979"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809002" href="?#comment-809002" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808979" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809002" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809002"> <div class="moveup"> <div class="ttypography"><p>:( I knew of this solution (it’s why ML is tight) but I didn’t realize that it could be done offline with small memory. Of course $$$K$$$ higher is obvious solution but main issue is that the extra modulos from binary exponentiation make it very hard to pass in Java without allowing other unoptimal solutions through such as precomputing inverses of the matrix. Probably $$$k=10^5$$$ would’ve been a better choice. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-809002 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809002 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809002"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808795" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zukonit14" style="position: relative;"> <img src='https://userpic.codeforces.org/1192187/avatar/5afd49be87fb87d9.jpg'/> </a> <div><a href="/profile/zukonit14" title="Expert zukonit14" class="rated-user user-blue">zukonit14</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808795" href="?#comment-808795" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808795" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1192187" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808795"> <div class="moveup"> <div class="ttypography"><p>Does Div2 D deserved to be D Problem? According to me it should've been Div2 E.</p></div> </div> </div> <div class="reply info"> <a class="comment-808795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808795"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808796" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mangat_angad" style="position: relative;"> <img src='https://userpic.codeforces.org/1449578/avatar/d3cadb0c26e0c11f.jpg'/> </a> <div><a href="/profile/mangat_angad" title="Specialist mangat_angad" class="rated-user user-cyan">mangat_angad</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808796" href="?#comment-808796" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808796" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1449578" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808796"> <div class="moveup"> <div class="ttypography"><p>I feel like such an idiot for not being able to understand problem C (Div2). For some reason I thought the nodes were connected like this — 1-&gt;2-&gt;3-&gt;....-&gt;N and that we had to minimise answer by adding other edges (of negative weight in case they dont give a negative cycle) to this graph.</p></div> </div> </div> <div class="reply info"> <a class="comment-808796 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808796 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808796"> <li> <div class="comment"> <table class="comment-table" commentId="808896" commentParentId="808796"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808896" href="?#comment-808896" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808796" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808896" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808896"> <div class="moveup"> <div class="ttypography"><p>But that's exactly what I did, and the final answer is the sum of the array — sum of all subarrays. <a href="https://codeforces.com/contest/1541/submission/120611950">120611950</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808896 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808896 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808896"> <li> <div class="comment"> <table class="comment-table" commentId="808941" commentParentId="808896"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808941" href="?#comment-808941" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808896" style="font-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="808941" 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="808941" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808941"> <div class="moveup"> <div class="ttypography"><p>No, that's not what you did. To compute the answer via the method described above, you would have to compute how many elements are lesser than the current element at any given iteration and add them and also keep and their count using a Fenwick tree/ BIT. That's the incorrect approach though because sorting would be more optimal.</p></div> </div> </div> <div class="reply info"> <a class="comment-808941 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808941 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808941"> <li> <div class="comment"> <table class="comment-table" commentId="808952" commentParentId="808941"> <tr> <td class="left"> <div style="position: absolute; left: 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/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808952" href="?#comment-808952" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808941" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808952" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808952"> <div class="moveup"> <div class="ttypography"><p>Sorry if I misunderstood things. mangat_angad only mentioned adding negative weighed edges to the 1-&gt;2-&gt;3-&gt;...N graph, which is what I thought to arrive at my solution. The array I mentioned is indeed sorted and formed by distance differences which are the weights in the 1-&gt;2-&gt;3-&gt;...N graph. Unfortunately I'm still too noob to understand the tree structures you mentioned.</p></div> </div> </div> <div class="reply info"> <a class="comment-808952 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808952 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808952"> <li> <div class="comment"> <table class="comment-table" commentId="808955" commentParentId="808952"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808955" href="?#comment-808955" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808952" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808955" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808955"> <div class="moveup"> <div class="ttypography"><p>Nothing unfortunate about it, logic trumps everything </p></div> </div> </div> <div class="reply info"> <a class="comment-808955 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808955 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808955"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808797" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808797" href="?#comment-808797" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808797" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808797"> <div class="moveup"> <div class="ttypography"><p>Just want to apologize to authors for the stupidest question, I misread the task..</p></div> </div> </div> <div class="reply info"> <a class="comment-808797 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808797 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808797"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808813" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808813" href="?#comment-808813" style="font-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="808813" 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="808813" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808813"> <div class="moveup"> <div class="ttypography"><p>Can someone tell me the meaning of this line in problem Div2D/Div1B<br /></p> <blockquote><p>Note that, until reaching, l every possible process still has the same probability of reaching b before a. Therefore, we can assume that the process has reached l and calculate the probability from there.</p> </blockquote><p>What same probability are they talking about?</p></div> </div> </div> <div class="reply info"> <a class="comment-808813 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808813 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808813"> <li> <div class="comment"> <table class="comment-table" commentId="808831" commentParentId="808813"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808831" href="?#comment-808831" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808813" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808831" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808831"> <div class="moveup"> <div class="ttypography"><p>Here's what it's trying to say:</p><p>Suppose we start by marking the root. To mark a or b, we must first mark the lca, so we may assume that the lca has just been marked.</p></div> </div> </div> <div class="reply info"> <a class="comment-808831 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808831 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808831"> <li> <div class="comment"> <table class="comment-table" commentId="808840" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808840" href="?#comment-808840" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808840" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808840"> <div class="moveup"> <div class="ttypography"><p>And what does this line mean? <em>&quot;The problem can be rephrased as having two stacks of size dist(l,a) and dist(l,b) with an arbitrary p to remove a node from one of the two stack (and 1−2p to nothing) and finding the probability that dist(l,b) reaches zero before dist(l,a).&quot;</em></p></div> </div> </div> <div class="reply info"> <a class="comment-808840 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808840 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808840"> <li> <div class="comment"> <table class="comment-table" commentId="808857" commentParentId="808840"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808857" href="?#comment-808857" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808840" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808857" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808857"> <div class="moveup"> <div class="ttypography"><p>Once you've reached the lca $$$l$$$, in a single step you either step closer to $$$a$$$, step closer to $$$b$$$, or step closer to neither.</p></div> </div> </div> <div class="reply info"> <a class="comment-808857 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808857 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808857"> <li> <div class="comment"> <table class="comment-table" commentId="808862" commentParentId="808857"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808862" href="?#comment-808862" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808857" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808862" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808862"> <div class="moveup"> <div class="ttypography"><p>Can you add implementation for this problem please?</p></div> </div> </div> <div class="reply info"> <a class="comment-808862 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808862 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808862"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808849" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808849" href="?#comment-808849" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808849" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808849"> <div class="moveup"> <div class="ttypography"><p>So, we mark lca first (of course). But why wouldn't it affect the final probability of reaching b before a? I mean, why is it sufficient to calculate the probability after marking lca?</p></div> </div> </div> <div class="reply info"> <a class="comment-808849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808849"> <li> <div class="comment"> <table class="comment-table" commentId="808873" commentParentId="808849"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808873" href="?#comment-808873" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808849" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808873" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808873"> <div class="moveup"> <div class="ttypography"><p>Before marking the lca, there is no way to make more progress towards $$$b$$$ than $$$a$$$ or vice versa. The subset of marked vertices also does not change the probability of moving towards $$$a$$$ or $$$b$$$ after reaching the lca because we're choosing uniformly at random and exactly two vertices are of interest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808873 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808873 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808873"> <li> <div class="comment"> <table class="comment-table" commentId="808883" commentParentId="808873"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808883" href="?#comment-808883" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808873" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808883" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808883"> <div class="moveup"> <div class="ttypography"><p>Now I get it. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808883 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808883 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808883"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808814" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808814" href="?#comment-808814" style="font-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="808814" 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="808814" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808814"> <div class="moveup"> <div class="ttypography"><p>So, my Solution for <strong>Div1 Problem B</strong> / <strong>Div2 Problem D</strong> / <strong>1540B — Tree Array</strong>:</p><p>Chose two Nodes $$$A$$$ and $$$B$$$ with $$$A&gt;B$$$. </p><p><strong>First DFS:</strong> Find the path from $$$A$$$ to $$$B$$$. I call it $$$path_p$$$. On $$$path_p$$$ mark the distance to $$$B$$$ for each node. </p><p><strong>Second DFS:</strong> For each remaining node $$$N$$$ find the shortest path to $$$path_p$$$. It will hit it at some node of the $$$path_p$$$ which has some distance $$$D$$$ marked on it. We mark $$$N$$$ with $$$D$$$. (See comment below for image.)</p><p><strong>Calculation:</strong> For each node $$$N$$$ we can calculate $$$P_i$$$. $$$P_i$$$ is the probability to reach Node $$$B$$$ before we reach Node $$$A$$$. We sum $$$P_i$$$ for each node. $$$P_i$$$ is also the probability, that the pair of Nodes $$$A$$$ and $$$B$$$ with starting node $$$N$$$ will contribute to the inversion sum. </p><p><strong>Iteration:</strong> We need to repeat this for each pair $$$A$$$ and $$$B$$$. In the end we divide the answer by $$$n$$$, the amount of nodes (the probability to start with Node $$$N$$$). </p><p>This algorithm is $$$O(N^3)$$$. See my Solution <a href="/contest/1540/submission/120603369" title="Посылка 120603369 от OleschY">120603369</a></p> <div class="spoiler"><b class="spoiler-title">How to calculate P_i</b><div class="spoiler-content" style="display: none;"><p>I wrote myself a small helper DP-program to find the regularities. Let $$$D$$$ be the Distance between $$$A$$$ and $$$B$$$ and $$$d$$$ be the distance from the node $$$N$$$ to $$$B$$$. My educated guess was: $$$P_i=\frac{\sum_{i=0}^{d-1}\binom{D-1}{i} }{2^{D-1}}$$$</p> <div class="spoiler"><b class="spoiler-title">Helper Program</b><div class="spoiler-content" style="display: none;"><p>It checks for a path of some length for each Intervall $$$[A,B]$$$ which is already visited, what the probability to reach one node before the other is. </p> <pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; int solve(int n) { vector&lt;vector&lt;double&gt;&gt; dp(n, vector&lt;double&gt;(n, 0)); for(int i = 0; i &lt; n; ++i) { dp[0][i] = 1; dp[i][n - 1] = 0; } dp[0][n - 1] = -1; for(int w = n; w &gt;= 0; w--) { for(int i = 1; i + w &lt; n - 1; i++) { int l = i; int r = w + i; dp[l][r] = 0.5 * (dp[l - 1][r] + dp[l][r + 1]); } } cout &lt;&lt; n &lt;&lt; &quot;\n\n&quot;; for(int i = 0; i &lt; n; i++) { cout &lt;&lt; dp[i][i]*(1&lt;&lt;(n-2)) &lt;&lt; &quot;\n&quot;; } cout &lt;&lt; &quot;\n\n\n\n&quot;; return 0; } //====================== // Technical stuff //====================== int main() { int ntest = 12; for(int test = 2; test &lt; ntest; ++test) { solve(test); } return 0; } </code></pre></div></div></div></div></div> </div> </div> <div class="reply info"> <a class="comment-808814 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808814 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808814"> <li> <div class="comment"> <table class="comment-table" commentId="808843" commentParentId="808814"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808843" href="?#comment-808843" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808814" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808843" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808843"> <div class="moveup"> <div class="ttypography"><p>Can you explain your solution in a little bit more detail? :')</p></div> </div> </div> <div class="reply info"> <a class="comment-808843 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808843 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808843"> <li> <div class="comment"> <table class="comment-table" commentId="808869" commentParentId="808843"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808869" href="?#comment-808869" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808843" style="font-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="808869" 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="808869" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808869"> <div class="moveup"> <div class="ttypography"><p>Oof, I can give you an image, that shows how the distances from the two DFS are distributed on an example. You can see Nodes $$$A$$$ and $$$B$$$ and the numbers are the distances we write into the nodes. </p><p><img alt=" " src="/predownloaded/d8/2f/d82f98ecd2c1b4bd15b3c40e62476f6ae2741a64.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>If you have specific questions about some steps go ahead and ask. </p></div> </div> </div> <div class="reply info"> <a class="comment-808869 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808869 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808869"> <li> <div class="comment"> <table class="comment-table" commentId="810069" commentParentId="808869"> <tr> <td class="left"> <div style="position: absolute; left: 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/Mrajaryan" style="position: relative;"> <img src='https://userpic.codeforces.org/1377953/avatar/e904b3a3a2eac1ad.jpg'/> </a> <div><a href="/profile/Mrajaryan" title="Newbie Mrajaryan" class="rated-user user-gray">Mrajaryan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 15:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810069" href="?#comment-810069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808869" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810069" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1377953" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810069"> <div class="moveup"> <div class="ttypography"><p>what does the dp states mean in your helper program? I am unable to understand. Can you please explain?</p></div> </div> </div> <div class="reply info"> <a class="comment-810069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810069"> <li> <div class="comment"> <table class="comment-table" commentId="810097" commentParentId="810069"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 18:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810097" href="?#comment-810097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-810069" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810097"> <div class="moveup"> <div class="ttypography"><p>You have Nodes $$$1$$$ through $$$N$$$, neighbouring IDs are connected. The state $$$dp[l][r]$$$ is the probability, that node $$$N$$$ will be reached before node $$$1$$$ with all the nodes $$$l$$$ through $$$r$$$ marked already. Obviously $$$dp[1][x]=0$$$ and $$$dp[x][N]=1$$$ ($$$dp[1][N]$$$ can't happen). The recurrence is $$$dp[l][r]=(dp[l-1][r]+dp[l][r+1])/2$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-810097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808818" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808818" href="?#comment-808818" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808818" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808818"> <div class="moveup"> <div class="ttypography"><p>I can't grasp the editorial of Div 2 D/ Div 1 B. Can somebody provide a more intuitive explanation?</p></div> </div> </div> <div class="reply info"> <a class="comment-808818 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808818 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808818"> <li> <div class="comment"> <table class="comment-table" commentId="808821" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:45">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808821" href="?#comment-808821" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808821" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808821"> <div class="moveup"> <div class="ttypography"><p>same :(</p></div> </div> </div> <div class="reply info"> <a class="comment-808821 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808821 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808821"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808861" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808861" href="?#comment-808861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808861" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808861"> <div class="moveup"> <div class="ttypography"><p>Step 1. use linearity of expectation. The answer is</p> <center>$$$\sum_{a&lt;b} P(b\text{ appears before }a). $$$</center><p>Step 2: Observe that if we start by marking a vertex $$$c$$$ on the path between $$$a$$$ and $$$b$$$, and suppose the next marked vertex on the path is $$$d$$$. Then, the probability that $$$d$$$ is between $$$c$$$ and $$$a$$$ and the probability that $$$d$$$ is between $$$c$$$ and $$$b$$$ are both $$$1/2$$$. This is because there are only two choices for $$$d$$$ and we're choosing uniformly at random. This means that the answer only depends on $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p><p>Step 3: run a dp to calculate the probability that we mark $$$b$$$ before $$$a$$$ given $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808861"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808833" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808833" href="?#comment-808833" style="font-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="808833" 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="808833" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-72" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-72</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808833"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin &gt;&gt; t; while(t--){ int n; cin &gt;&gt; n; long long arr[n]; for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0; for(int i = 0; i &lt; n — 1; i++){ for(int j = arr[i] — 2 — i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } } } cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;; } return 0; }</p><p>/* Accepted code A different approach using arrays (as I don't know what vectors are, haven't read that) I hope this is a optimal approach. Any suggestions related to this are whole-heartedly welcomed. Also, please guide me how could I have optimized the code to a much extent. Thanks in advance! Keep programming! */</p></div> </div> </div> <div class="reply info"> <a class="comment-808833 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808833 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808833"> <li> <div class="comment"> <table class="comment-table" commentId="808844" commentParentId="808833"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808844" href="?#comment-808844" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808833" style="font-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="808844" 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="808844" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-35" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808844"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-808844 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808844 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808844"> <li> <div class="comment"> <table class="comment-table" commentId="808863" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808863" href="?#comment-808863" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808863" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808863"> <div class="moveup"> <div class="ttypography"><p>Not studied yet, I'm still a beginner, but planning to start soon. Thanks for the guidance.</p></div> </div> </div> <div class="reply info"> <a class="comment-808863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808863"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808879" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808879" href="?#comment-808879" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808879" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808879"> <div class="moveup"> <div class="ttypography"><p>once upon a time, I also did problems while not know what vectors are. sad times :'(</p></div> </div> </div> <div class="reply info"> <a class="comment-808879 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808879 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808879"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808926" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808926" href="?#comment-808926" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808926" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808926"> <div class="moveup"> <div class="ttypography"><p>There's no issue in not knowing vectors. Yes they are important I agree but not knowing vectors should not be discouraged. I became expert here without knowing anything about vectors plus he is a beginner so he shouldn't be discouraged like this.</p></div> </div> </div> <div class="reply info"> <a class="comment-808926 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808926 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808926"> <li> <div class="comment"> <table class="comment-table" commentId="808927" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Tech.Maniac" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Tech.Maniac" title="Expert Tech.Maniac" class="rated-user user-blue">Tech.Maniac</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808927" href="?#comment-808927" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808927" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1242860" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808927"> <div class="moveup"> <div class="ttypography"><p>+1, I agree with you. Same I was expert last year solely using arrays</p></div> </div> </div> <div class="reply info"> <a class="comment-808927 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808927 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808927"> <li> <div class="comment"> <table class="comment-table" commentId="809201" commentParentId="808927"> <tr> <td class="left"> <div style="position: absolute; left: 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/Yash.Amin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Yash.Amin" title="Specialist Yash.Amin" class="rated-user user-cyan">Yash.Amin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809201" href="?#comment-809201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808927" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809201" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-28" data-commentUserId="1226462" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-28</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809201"> <div class="moveup"> <div class="ttypography"><p>Bas kar bsdk kitna jhooth bolega</p></div> </div> </div> <div class="reply info"> <a class="comment-809201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809201"> <li> <div class="comment"> <table class="comment-table" commentId="809215" commentParentId="809201"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809215" href="?#comment-809215" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809215" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809215"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-blue" href="/profile/Yash.Amin" title="Эксперт Yash.Amin">Yash.Amin</a> Could you please refrain from using foul language on educational discussions. Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-809215 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809215 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809215"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808928" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808928" href="?#comment-808928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808928" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808928"> <div class="moveup"> <div class="ttypography"><p>Ah my bad, I did not want to come across as being arrogant, but I was genuinely confused that some people did not know vectors although they are using C++.</p></div> </div> </div> <div class="reply info"> <a class="comment-808928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808928"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808839" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamkiller04" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dreamkiller04" title="Newbie dreamkiller04" class="rated-user user-gray">dreamkiller04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808839" href="?#comment-808839" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2089608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808839"> <div class="moveup"> <div class="ttypography"><p>Please add implementations too.</p></div> </div> </div> <div class="reply info"> <a class="comment-808839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808839"> <li> <div class="comment"> <table class="comment-table" commentId="809106" commentParentId="808839"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809106" href="?#comment-809106" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808839" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809106" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809106"> <div class="moveup"> <div class="ttypography"><p>Simply running two loops and checking every case would give a TLE. So, we might want to minimize the number of operations. For this, we would only consider the cases where the sum of indices is a multiple of an element.</p><p>For this, we would first create two loops, one within the other, first loop iterating i from 0 to (n — 1) with an incrementation of 1. By observation, we can see that the first index for which the sum of indices will be a multiple of arr[i] is (arr[i] — 2 — i).</p><p>So, in the nested loop we will run j = (arr[i] — 2 — i) till (n — 1) with an incrementation of arr[i]. We would ignore the cases where j &lt; 0 or j &gt;= n.</p><p>Finally, we need to check for how many cases this holds (arr[i] * arr[j] = i + j + 2 and j &gt; i).</p><p>Suggestions are welcomed!</p></div> </div> </div> <div class="reply info"> <a class="comment-809106 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809106 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809106"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808842" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808842" href="?#comment-808842" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808842" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-64" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-64</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808842"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){</p><p>ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);</p><p>int t;</p><p>cin &gt;&gt; t;</p><p>while(t--){</p><p>int n;</p> <pre>cin &gt;&gt; n;</pre><p>long long arr[n];</p> <pre>for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0;</pre><p>for(int i = 0; i &lt; n — 1; i++){</p> <pre>for(int j = arr[i] &amp;mdash; 2 &amp;mdash; i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } }</pre><p>}</p><p>cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;;</p><p>}</p> <pre>return 0;</pre><p>}</p><p>/* Accepted code</p><p>A different approach using arrays (as I don't know what vectors are, haven't read that)</p><p>I hope this is a optimal approach.</p><p>Any suggestions related to this are whole-heartedly welcomed.</p><p>Also, please guide me how could I have optimized the code to a much extent.</p><p>Thanks in advance!</p><p>Keep programming! </p><p>*/</p></div> </div> </div> <div class="reply info"> <a class="comment-808842 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808842 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808842"> <li> <div class="comment"> <table class="comment-table" commentId="808851" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808851" href="?#comment-808851" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808851" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808851"> <div class="moveup"> <div class="ttypography"><p>Use spoilers for writing codes, please!</p></div> </div> </div> <div class="reply info"> <a class="comment-808851 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808851 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808851"> <li> <div class="comment"> <table class="comment-table" commentId="808870" commentParentId="808851"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808870" href="?#comment-808870" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808851" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808870" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808870"> <div class="moveup"> <div class="ttypography"><p>Actually, this is my first comment. Don't know much of this stuff as of now, but I'll surely take care of it the very next time.</p></div> </div> </div> <div class="reply info"> <a class="comment-808870 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808870 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808870"> <li> <div class="comment"> <table class="comment-table" commentId="809760" commentParentId="808870"> <tr> <td class="left"> <div style="position: absolute; left: 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/sus" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sus" title="Pupil sus" class="rated-user user-green">sus</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 05:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809760" href="?#comment-809760" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808870" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809760" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1749651" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809760"> <div class="moveup"> <div class="ttypography"><p>what problem is your code for</p></div> </div> </div> <div class="reply info"> <a class="comment-809760 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809760 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809760"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808884" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sevlll777" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sevlll777" title="Grandmaster sevlll777" class="rated-user user-red">sevlll777</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808884" href="?#comment-808884" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808884" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="839333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808884"> <div class="moveup"> <div class="ttypography"><p>NICE CODESTYLE!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-808884 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808884 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808884"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809084" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cj2021" style="position: relative;"> <img src='https://userpic.codeforces.org/1927237/avatar/b64ff59bd9dcf385.jpg'/> </a> <div><a href="/profile/cj2021" title="Newbie cj2021" class="rated-user user-gray">cj2021</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809084" href="?#comment-809084" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809084" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1927237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809084"> <div class="moveup"> <div class="ttypography"><p>What is &amp;mdash?</p><p>Just curious to know as haven't seen it before.</p></div> </div> </div> <div class="reply info"> <a class="comment-809084 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809084 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809084"> <li> <div class="comment"> <table class="comment-table" commentId="809097" commentParentId="809084"> <tr> <td class="left"> <div style="position: absolute; left: 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/klahsiv" style="position: relative;"> <img src='https://userpic.codeforces.org/1590145/avatar/1bf86ae3d48e55b.jpg'/> </a> <div><a href="/profile/klahsiv" title="Expert klahsiv" class="rated-user user-blue">klahsiv</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809097" href="?#comment-809097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809084" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590145" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809097"> <div class="moveup"> <div class="ttypography"><p>it is minus (-).</p></div> </div> </div> <div class="reply info"> <a class="comment-809097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808848" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/willy108" style="position: relative;"> <img src='https://userpic.codeforces.org/1439320/avatar/d7f79ed4e8b32e9a.jpg'/> </a> <div><a href="/profile/willy108" title="Master willy108" class="rated-user user-orange">willy108</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808848" href="?#comment-808848" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808848" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="1439320" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808848"> <div class="moveup"> <div class="ttypography"><p>Div2 B can also be done in O(NsqrtN). We know that for a given pair of indeces i+j &lt; 2n, so any pair that a[i] * a[j] &lt; 2n will have to have one of the two terms be &lt;= sqrt(n) (with some off by one errors of course). So the algorithm is to store an array of pairs [array value, index] and sort that array by the value. If the array value is &lt;= sqrt(2n) we can naively loop over the rest of the array in O(n) time and check (be careful about overcount), and if the value is &gt; sqrt(n), we can ignore it. This works since when a[i] * a[j] &lt; 2n one of a[i] or a[j] has to be &lt;= sqrt(2n) and as a result, every pair will be counted.</p></div> </div> </div> <div class="reply info"> <a class="comment-808848 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808848 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808848"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808860" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bcollet" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bcollet" title="Master bcollet" class="rated-user user-orange">bcollet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808860" href="?#comment-808860" style="font-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="808860" 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="808860" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="858059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808860"> <div class="moveup"> <div class="ttypography"><p>I don't understand in div1 C why it's prefix of b, in the case i=3 we have $$$a_1+a_2+a_3=f_1+f_1+b_1+f_1+b_1+b_2$$$ so $$$f_1=(ap_i-2b_1-b_2)$$$ I believe the general formula is something in the taste of $$$f_1=(ap_i-ibp_{i-1}+bpt_{i-1})/i$$$ where bpt_i=b_1+2b_2+...+ib_i, I think I miss something<br />Edit: corrected</p></div> </div> </div> <div class="reply info"> <a class="comment-808860 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808860 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808860"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808865" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ParsaS" style="position: relative;"> <img src='https://userpic.codeforces.org/1590150/avatar/dc2d8c002d2c5e1e.jpg'/> </a> <div><a href="/profile/ParsaS" title="Candidate Master ParsaS" class="rated-user user-violet">ParsaS</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808865" href="?#comment-808865" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808865" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590150" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808865"> <div class="moveup"> <div class="ttypography"><p>Nice problems. thanks for almost fast editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-808865 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808865 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808865"> <li> <div class="comment"> <table class="comment-table" commentId="808871" commentParentId="808865"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/E404_Not_Found" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/E404_Not_Found" title="Expert E404_Not_Found" class="rated-user user-blue">E404_Not_Found</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808871" href="?#comment-808871" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808865" style="font-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="808871" 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="808871" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1662858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808871"> <div class="moveup"> <div class="ttypography"><p>Yes thanks for fast editorial :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808871 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808871 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808871"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808890" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vikash_8090_b" style="position: relative;"> <img src='https://userpic.codeforces.org/1969032/avatar/a0f23c893ae54e74.jpg'/> </a> <div><a href="/profile/vikash_8090_b" title="Newbie vikash_8090_b" class="rated-user user-gray">vikash_8090_b</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808890" href="?#comment-808890" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808890" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="1969032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808890"> <div class="moveup"> <div class="ttypography"><p>is there anyone who can't even solve one question of today's contest ..</p></div> </div> </div> <div class="reply info"> <a class="comment-808890 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808890 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808890"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808892" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808892" href="?#comment-808892" style="font-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="808892" 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="808892" class="CommentVoteFrame" data-commentRating="-6" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808892"> <div class="moveup"> <div class="ttypography"><p>Deleted :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808892 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808892 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808892"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808918" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prituladima" style="position: relative;"> <img src='https://userpic.codeforces.org/116750/avatar/ca46d0256a294b26.jpg'/> </a> <div><a href="/profile/prituladima" title="Pupil prituladima" class="rated-user user-green">prituladima</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808918" href="?#comment-808918" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808918" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="116750" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808918"> <div class="moveup"> <div class="ttypography"><p>Please explain div2c/div1a problem a little bit more. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808918 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808918 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808918"> <li> <div class="comment"> <table class="comment-table" commentId="808921" commentParentId="808918"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808921" href="?#comment-808921" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808918" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808921" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808921"> <div class="moveup"> <div class="ttypography"><p>Try out this <a href="https://youtube.com/c/MagentaCobra">channel</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808921 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808921 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808921"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808950" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jakab922" style="position: relative;"> <img src='https://userpic.codeforces.org/53532/avatar/f9515e974f3ebcb1.jpg'/> </a> <div><a href="/profile/jakab922" title="Specialist jakab922" class="rated-user user-cyan">jakab922</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808950" href="?#comment-808950" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808950" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="53532" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808950"> <div class="moveup"> <div class="ttypography"><p>I don't really understand the need for a recursive function for the stack emptying probabilities in <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a>. I mean given that you have a stack of size <code>n</code> and and <code>m</code> you can basically have an array of size <code>n + m</code> filled with <code>0</code>s and <code>1</code>s where <code>0</code> at the <code>i</code>th place means that the <code>i</code>th element was taken from the first stack. Any such array which has <code>n</code> <code>0</code>s and <code>m</code> <code>1</code>s correspond to one process and it's easy to see that whoever takes the last spot in the array gets emptied later which gives an easy way to calculate the probabilities. Namely $$$\binom{n + m - 1}{n - 1} / \binom{n + m}{n}$$$ for the first and similar to the other. </p></div> </div> </div> <div class="reply info"> <a class="comment-808950 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808950 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808950"> <li> <div class="comment"> <table class="comment-table" commentId="808959" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cuom1999" style="position: relative;"> <img src='https://userpic.codeforces.org/253776/avatar/934152bc42a0b10c.jpg'/> </a> <div><a href="/profile/cuom1999" title="Grandmaster cuom1999" class="rated-user user-red">cuom1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808959" href="?#comment-808959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="253776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808959"> <div class="moveup"> <div class="ttypography"><p>If $$$m=2$$$ and $$$n=1$$$, your approach gives $$$\frac{1}{3}$$$. The correct answer should be $$$\frac{1}{4}$$$. </p><p>P/S: I'm also curious if there is any combinatoric approach for this,<a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808959"> <li> <div class="comment"> <table class="comment-table" commentId="809004" commentParentId="808959"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809004" href="?#comment-809004" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809004" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809004"> <div class="moveup"> <div class="ttypography"><p>I would guess that there’s no easy closed form. You can evaluate in $$$O(n)$$$ however by counting right up paths from $$$(a,0)$$$ to $$$(x,y)$$$ for all $$$a$$$ and multiplying by $$$2^{-steps}$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-809004 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809004 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809004"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809366" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/geekpradd" style="position: relative;"> <img src='https://userpic.codeforces.org/367430/avatar/427394aa7f5a63a0.jpg'/> </a> <div><a href="/profile/geekpradd" title="Candidate Master geekpradd" class="rated-user user-violet">geekpradd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809366" href="?#comment-809366" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809366" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="367430" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809366"> <div class="moveup"> <div class="ttypography"><p>The problem with this is that all the possibilities are not equilikely, consider $$$m=2, n=1$$$ and let $$$1$$$ denote entries from the stack of size $$$n$$$. Then the probability of obtaining $$$100$$$ is $$$1/2$$$, while obtaining $$$010$$$ and $$$001$$$ has a probability of $$$1/4$$$. Your approach assumes a uniform prior probability (in which case the answer is indeed $$$1/3$$$ whereas here it is $$$1/4$$$ which is the probability of getting $$$001$$$)</p></div> </div> </div> <div class="reply info"> <a class="comment-809366 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809366 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809366"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thunderboltz" style="position: relative;"> <img src='https://userpic.codeforces.org/1170396/avatar/4f017b259605bc5c.jpg'/> </a> <div><a href="/profile/thunderboltz" title="Newbie thunderboltz" class="rated-user user-gray">thunderboltz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808951" href="?#comment-808951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170396" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808951"> <div class="moveup"> <div class="ttypography"><p>Problem Div2C/Div1A, Plz somebody explain 3rd hint. I didn't get why this condition must be true </p><p><code>The sum of the values of edges with positive weight must be ≥ the maximum value in the array.</code></p></div> </div> </div> <div class="reply info"> <a class="comment-808951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808951"> <li> <div class="comment"> <table class="comment-table" commentId="808995" commentParentId="808951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808995" href="?#comment-808995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808995" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808995"> <div class="moveup"> <div class="ttypography"><p>I like to think about C this way: The cheapest node is the root, and the most expensive node, X, is the one with the highest value, D. Therefore no matter how we make our edges, we need at least 1 path from node to X with distance D. So let's build 1 single edge of positive weight from 1 to X with weight D.</p><p>Now from node X, all other nodes are &lt;= D. We can use negative edges to go there. Now the problem just becomes &quot;assign as many negative edges as possible&quot; to the rest of the nodes. </p></div> </div> </div> <div class="reply info"> <a class="comment-808995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808995"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808971" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808971" href="?#comment-808971" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808971" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808971"> <div class="moveup"> <div class="ttypography"><p>In problem <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a> I agree with everything up to:</p> <blockquote><p>Once l is reached, we now note that the probability that the process &quot;gets closer&quot; to b is always equal to the probability of getting closer to a.</p> </blockquote><p>I agree with this quote if it was about each individual set of marked nodes and single step for them. Because for any individual set of marked nodes, those probabilities is just one over the number of options at the moment. But I don't understand why I should forget about everything else what happens with other parts of tree, because after single step which is neither towards <strong>a</strong> neither towards <strong>b</strong>, the number of options (nodes we can mark on next step) may change.</p></div> </div> </div> <div class="reply info"> <a class="comment-808971 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808971 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808971"> <li> <div class="comment"> <table class="comment-table" commentId="809006" commentParentId="808971"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809006" href="?#comment-809006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808971" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809006" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809006"> <div class="moveup"> <div class="ttypography"><p>That is correct, but to see how it stays the same you can think of it inductively. Use strong induction and assume probability is the same no matter what the state of the tree is. Then from $$$(x,y)$$$ you always have an equal probability of ending up in one of the two states you can transition to because $$$p$$$ is always the same. Every scenario you enter one state, there’s another scenario with the same probability that enters the other state. So, the probability of entering one of the two states is the same as the other, thus $$$0.5$$$. Hopefully that makes things more clear.</p></div> </div> </div> <div class="reply info"> <a class="comment-809006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809006"> <li> <div class="comment"> <table class="comment-table" commentId="809113" commentParentId="809006"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809113" href="?#comment-809113" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809006" style="font-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="809113" 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="809113" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809113"> <div class="moveup"> <div class="ttypography"><p>Oh thanks, it's clear now. So, base of induction is when only <strong>l</strong> reached, and we can show that probability to make step towards <strong>a</strong> and <strong>b</strong> is same because for each individual set you can go from <strong>l</strong> to <strong>b</strong> instead of going from <strong>l</strong> into <strong>a</strong>, using exactly same steps in between (those steps which doesn't change distances to <strong>a</strong> and <strong>b</strong>). And similar holds for next steps.</p></div> </div> </div> <div class="reply info"> <a class="comment-809113 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809113 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809113"> <li> <div class="comment"> <table class="comment-table" commentId="821713" commentParentId="809113"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 08:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821713" href="?#comment-821713" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809113" style="font-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="821713" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="821713" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-821713"> <div class="moveup"> <div class="ttypography"><p>Can you explain this?</p><p>Assume $$$X$$$ is initially node we chose. Then define a function $$$g$$$ :</p><p>$$$g[a][b][STATE]$$$ = probability to reach a before b while state of the tree we reach is $$$STATE$$$, and $$$a$$$, $$$b$$$ is length of path.</p><p><img alt=" " src="/predownloaded/c2/32/c232d053fe3fbd1dedc06e56db58a7c139157987.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>follow the image, I can see : $$$g[a][b][STATE_x] = \frac{1}{4} (g[a][b][STATE_d] + g[a][b][STATE_e] + g[a — 1][b][closer_a] + g[a][b — 1][closer_b])$$$</p><p>It can easy see that the probability can change. Or I wrong in some where?</p></div> </div> </div> <div class="reply info"> <a class="comment-821713 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821713 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821713"> <li> <div class="comment"> <table class="comment-table" commentId="821861" commentParentId="821713"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 18:25">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821861" href="?#comment-821861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821713" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="821861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-821861"> <div class="moveup"> <div class="ttypography"><p>I'll hide my long explanation under spoiler</p> <div class="spoiler"><b class="spoiler-title">horrible wall of text</b><div class="spoiler-content" style="display: none;"><p>To put things into words, I want to define some things. First, suppose we marked some $$$s_1, s_2, s_3 ... s_k$$$ vertices in exact this order. Then, let $$$P(s)$$$ to be probability to mark them in this sequence. It can be decomposed into $$$P(s) = p_1 \cdot p_2 \cdot p_3 \cdot ... \cdot p_k$$$ where $$$p_i = 1/o_{i-1}$$$ where $$$o_i$$$ is number of options at step $$$i$$$ — number of opened vertices, except $$$p_0 = 1/n$$$, or $$$o_0 = n$$$.</p><p>Then, let $$$l = LCA(a, b)$$$ where $$$LCA$$$ is lowest common ancestor. Then, let $$$x_v$$$ to be some sort of 'cost'. For each $$$v$$$ on path between $$$a$$$ and $$$l$$$ it will be distance to $$$l$$$, and $$$-1$$$ everywhere else. Similarly, for each $$$v$$$ on path between $$$b$$$ and $$$l$$$ let $$$y_v$$$ to be distance to $$$l$$$ and $$$-1$$$ everywhere else. Let</p> <center>$$$ A(s) = \max\limits_{v\in s}x_v \\ B(s) = \max\limits_{v\in s}y_v $$$</center><p>Then $$$A(s)$$$ is equal to how far we reach $$$a$$$, and $$$B(s)$$$ is equal to how far we reach $$$b$$$. Let say we are in situation $$$(A(s), B(s))$$$ after marking $$$s$$$, and therefore situation is pair of numbers. Situation $$$(-1,-1)$$$ corresponds that no vertex is marked on path from $$$a$$$ to $$$b$$$. Situation $$$(0,0)$$$ corresponds to only $$$l$$$ marked on path from $$$a$$$ to $$$b$$$. And situation $$$(1,0)$$$ corresponds to $$$l$$$ and single vertex towards $$$a$$$ is marked.</p><p>Finally, let say sequence of marks $$$s$$$ reached state $$$(A(s), B(s))$$$ if either $$$A(s) = x_{s_k}$$$ or $$$B(s) = y_{s_k}$$$, in other words, last vertex is on path from $$$a$$$ to $$$b$$$ and it did change situation.</p><p>Now, what we want to prove is following:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha+1,\beta)} P(s) = \sum\limits_{s\;reached\;(\alpha,\beta+1)} P(s)$$$</center><p><strong>For some fixed</strong> $$$s_1$$$, which is root we chosen. And the way we prove it is that $$$s$$$ that is reached $$$(\alpha+1,\beta)$$$ consists of $$$u$$$ that reached $$$(\alpha,\beta)$$$ plus additional steps: $$$w$$$ plus $$$s_k$$$. So $$$s = u..w..s_k$$$ where $$$..$$$ is concatenation. It's easy to see what none of vertices from $$$w$$$ is on path from $$$a$$$ to $$$b$$$. Also, it's easy to see that we could instead of choosing $$$s_k$$$ could choose vertex $$$z$$$ towards $$$b$$$, and it would have same probability. In other words $$$P(s) = P(u..w..z)$$$. And this $$$u..w..z$$$ should reach state $$$(\alpha, \beta+1)$$$. So it should be in right side sum of our equation we want to prove.</p><p>So, for any $$$s$$$ from left sum, we can make $$$s'$$$ from right sum in unique way, and it will have same $$$P(s) = P(s')$$$. Similarly, for any $$$s$$$ from right sum, we can make $$$s'$$$ from left sum in unique way, and it will have same $$$P(s) = P(s')$$$. So this is bijection, and each element from left sum corresponds to element from right sum with same value, so those sums should have same value. Therefore it's equality.</p><p>Initially I wanted to trim $$$s$$$ from $$$(\alpha+1,\beta)$$$ to $$$(\alpha,\beta)$$$ and show similar thing based on following sum:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha,\beta)} P(s)$$$</center><p>Which is probability to reach state $$$(\alpha, \beta)$$$, but luckily it didn't required. I'll use notation $$$P(reach(\alpha, \beta))$$$ for this probability.</p><p>Thing that is not covered though: why this equality can be translated into probability $$$= 1/2$$$? Well, from $$$(\alpha, \beta)$$$ you eventually will reach either $$$(\alpha+1,\beta)$$$ or $$$(\alpha,\beta+1)$$$, so you can see this as example of Law of total probability. $$$P(reach(\alpha, \beta)) = P(reach (\alpha+1, \beta)) + P(reach (\alpha, \beta+1))$$$, because events $$$(\alpha+1,\beta)$$$ and $$$(\alpha,\beta+1)$$$ are disjoint events given $$$(\alpha, \beta)$$$ is reached. And we proved they have equal probability so $$$P(reach(\alpha, \beta)) = 2\cdot P(reach (\alpha+1, \beta))$$$, so $$$P(reach (\alpha+1, \beta)) = 1/2\cdot P(reach(\alpha, \beta))$$$ which we actually use.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-821861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821861"> <li> <div class="comment"> <table class="comment-table" commentId="822027" commentParentId="821861"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/28/2021 13:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822027" href="?#comment-822027" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821861" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="822027" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822027"> <div class="moveup"> <div class="ttypography"><p>Oh, sorry, there is one missing part. We proved $$$P(reached(\alpha+1,\beta))=P(reached(\alpha,\beta+1))$$$ <strong>given</strong> $$$(\alpha,\beta)$$$ is reached, but this is actually what we need. This <strong>given</strong> condition is what I missed. Without <strong>given</strong> we could reach $$$(\alpha+1,\beta)$$$ from reaching $$$(\alpha+1,\beta-1)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-822027 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822027 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822027"> <li> <div class="comment"> <table class="comment-table" commentId="822370" commentParentId="822027"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 13:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822370" href="?#comment-822370" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822027" style="font-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="822370" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="822370" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822370"> <div class="moveup"> <div class="ttypography"><p>Thanks for amz explain. I realize that I had some missunderstand in the way we calc $$$P(reach\ A\ before\ B)$$$</p><p>This's exactly what in my mind one day ago: let $$$s = ...a...b...$$$ where $$$a$$$ and $$$b$$$ is node $$$a$$$ and node $$$b$$$, &quot;$$$...$$$&quot; mean some node between them which we chose them in exactly that order, or in other word, $$$s$$$ is state represent what we chose (exact in this order) I think $$$P(reach\ A\ before\ B)$$$ (or $$$P(A&lt;B)$$$) must be calculate in this way :</p><p>$$$P(A&lt;B) = \sum_{\substack{all\ s\ which\ a&lt;b}} P(s)$$$</p><p>But unfortunately, it's wrong (may be, or I still missunderstanding)</p><p>$$$P(A) = \sum_{\substack{all\ B[i]\ \subseteq\ A}} P(B[i])$$$ if and only if all $$$B[i]$$$ are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-822370 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822370 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822370"> <li> <div class="comment"> <table class="comment-table" commentId="822755" commentParentId="822370"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 22:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822755" href="?#comment-822755" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822370" style="font-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="822755" 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="822755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822755"> <div class="moveup"> <div class="ttypography"><p>$$$P(A &lt; B)$$$ in your terms is exactly what we need (if a = A and b = B).</p><p>I don't understand last formula, everything else looks fine.</p><p>And to find $$$P(A &lt; B)$$$ we use fact above and calculate all possible ways to reach $$$a$$$ earlier than $$$b$$$ we use $$$(\alpha, \beta)$$$ states using my notation: you either get $$$\alpha$$$ equal to dist to $$$a$$$ when $$$\beta$$$ = 0, or $$$\beta$$$ = 1, or 2, or 3...</p> <center>$$$ P(A &lt; B) = \\ =\sum\limits_{i=0}^{dist(b,l)}P(reach(dist(a,l),i)\;given\; reached(dist(a,l)-1,i)) \\ = \sum\limits_{i=0}^{dist(b,l)}P(reached(dist(a,l)-1,i))\cdot \frac{1}{2} $$$</center><p>Or you can rephrase task into other task with two kind of balls. What probability to remove all balls of one kind earlier than other, if you pick one or other kind of ball with probability 1/2.</p></div> </div> </div> <div class="reply info"> <a class="comment-822755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822755"> </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="808983" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/xsc" style="position: relative;"> <img src='https://userpic.codeforces.org/343/avatar/9eaf243b1eb8c3d4.jpg'/> </a> <div><a href="/profile/xsc" title="Specialist xsc" class="rated-user user-cyan">xsc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808983" href="?#comment-808983" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808983" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="343" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808983"> <div class="moveup"> <div class="ttypography"><p>Div2 D, O(N^4) solution <a href="/contest/1541/submission/120623566" title="Посылка 120623566 от xsc">120623566</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808983 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808983 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808983"> <li> <div class="comment"> <table class="comment-table" commentId="809278" commentParentId="808983"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DavidXu_JJ" style="position: relative;"> <img src='https://userpic.codeforces.org/2003708/avatar/623dc8036b4e9d72.jpg'/> </a> <div><a href="/profile/DavidXu_JJ" title="Expert DavidXu_JJ" class="rated-user user-blue">DavidXu_JJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809278" href="?#comment-809278" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808983" style="font-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="809278" 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="809278" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2003708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809278"> <div class="moveup"> <div class="ttypography"><p>Your code really helps me a lot in debugging,thanks.</p><p>By the way,it's weired that I get Wrong6 when I try to optimize to O(N^3*logN) by binary search on tree.</p><p>I have tested my function on other online judge and my function seems to be correct.</p></div> </div> </div> <div class="reply info"> <a class="comment-809278 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809278 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809278"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809018" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ducati" style="position: relative;"> <img src='https://userpic.codeforces.org/699102/avatar/eff3c352646e914e.jpg'/> </a> <div><a href="/profile/ducati" title="Grandmaster ducati" class="rated-user user-red">ducati</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 03:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809018" href="?#comment-809018" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809018" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="699102" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809018"> <div class="moveup"> <div class="ttypography"><p>Although Div.2 D is harder than ever, in my opinion, it's such a useful and excellent problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-809018 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809018 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809018"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809046" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KanishkGoel" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/KanishkGoel" title="Expert KanishkGoel" class="rated-user user-blue">KanishkGoel</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809046" href="?#comment-809046" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809046" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1917239" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809046"> <div class="moveup"> <div class="ttypography"><p>Is it usual for people to post solutions online during the contest like this channel? <a href="https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ">https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809046 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809046 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809046"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809051" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809051" href="?#comment-809051" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809051"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain why this submission <a href="/contest/1541/submission/120562335" title="Посылка 120562335 от Karnania7201">120562335</a> is failing for Div2 B? It would be a great help.</p></div> </div> </div> <div class="reply info"> <a class="comment-809051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809051"> <li> <div class="comment"> <table class="comment-table" commentId="809076" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809076" href="?#comment-809076" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809076" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809076"> <div class="moveup"> <div class="ttypography"><p>Bro you did not included the condition that i and j should be different i.e (i != j) because it is given in question that no are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-809076 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809076 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809076"> <li> <div class="comment"> <table class="comment-table" commentId="809079" commentParentId="809076"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:08">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809079" href="?#comment-809079" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809076" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809079" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809079"> <div class="moveup"> <div class="ttypography"><p>I think its covered as I started j from i+1. I tried that explicitly too but it didn't work. I wrote the same idea in a different way and it worked but this kind of implementation is not working.</p></div> </div> </div> <div class="reply info"> <a class="comment-809079 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809079 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809079"> <li> <div class="comment"> <table class="comment-table" commentId="809082" commentParentId="809079"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809082" href="?#comment-809082" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809079" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809082" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809082"> <div class="moveup"> <div class="ttypography"><p>yeah, you are right, I run your code using vector instead of creating memeset it worked fine, i guess there is some problem in that. <a href="https://codeforces.com/contest/1541/submission/120633207">120633207</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809082 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809082 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809082"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809081" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_NICkk" style="position: relative;"> <img src='https://userpic.codeforces.org/1543175/avatar/6084dd87f2c1cad9.jpg'/> </a> <div><a href="/profile/_NICkk" title="Expert _NICkk" class="rated-user user-blue">_NICkk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809081" href="?#comment-809081" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809081" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1543175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809081"> <div class="moveup"> <div class="ttypography"><p>Only fault in your code is that you didn't used memset correctly </p><p>I just changed your memset with this &quot; memset(ind, 0, sizeof(ind)) &quot; and it worked perfectly fine</p></div> </div> </div> <div class="reply info"> <a class="comment-809081 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809081 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809081"> <li> <div class="comment"> <table class="comment-table" commentId="809091" commentParentId="809081"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:37">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809091" href="?#comment-809091" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809081" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809091" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809091"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot to both of you. I shouldn't have used it without properly knowing about it. </p></div> </div> </div> <div class="reply info"> <a class="comment-809091 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809091 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809091"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809064" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vrintle" style="position: relative;"> <img src='https://userpic.codeforces.org/1991777/avatar/24d9007095afbbb6.jpg'/> </a> <div><a href="/profile/vrintle" title="Master vrintle" class="rated-user user-orange">vrintle</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809064" href="?#comment-809064" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809064" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1991777" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809064"> <div class="moveup"> <div class="ttypography"><p>Instead of $$$a_i \cdot a_j \leq 2n$$$, we could also check $$$a_i \cdot a_j \leq i+n$$$ which is a bit faster ($$$ \sim 62ms$$$).</p></div> </div> </div> <div class="reply info"> <a class="comment-809064 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809064 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809064"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809066" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809066" href="?#comment-809066" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809066" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809066"> <div class="moveup"> <div class="ttypography"><p>can anyone explain B. pleasant pairs more easy words?? </p></div> </div> </div> <div class="reply info"> <a class="comment-809066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809066"> <li> <div class="comment"> <table class="comment-table" commentId="809067" commentParentId="809066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809067" href="?#comment-809067" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809067" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809067"> <div class="moveup"> <div class="ttypography"><p>And also what is ask in 3rd question i cant understand what asked in it</p></div> </div> </div> <div class="reply info"> <a class="comment-809067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809067"> <li> <div class="comment"> <table class="comment-table" commentId="809070" commentParentId="809067"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809070" href="?#comment-809070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809067" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809070"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">https://www.youtube.com/watch?v=xCj_ZR5kENo</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809098" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809098" href="?#comment-809098" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809098" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809098"> <div class="moveup"> <div class="ttypography"><p>For those who are searching for a simple solution for great Graphs problems in O (nlogn). <a href="https://codeforces.com/contest/1541/submission/120600816">https://codeforces.com/contest/1541/submission/120600816</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809098 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809098 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809098"> <li> <div class="comment"> <table class="comment-table" commentId="809119" commentParentId="809098"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fjvzr" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/fjvzr" title="Newbie fjvzr" class="rated-user user-gray">fjvzr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809119" href="?#comment-809119" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809098" style="font-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="809119" 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="809119" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1623986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809119"> <div class="moveup"> <div class="ttypography"><p>Bro can u explain this soln????? i thought of taking all pairs that give negative edges except for the adjacent pairs.... bt getting wrong ans in 3rd 4th test case.....</p><p>while(n&gt;2) { sum-=(n-2)*(llabs(a[j]-a[i])); n--; // n = size i++; // i = 0 j--; // j = n-1 } cout&lt;&lt;sum&lt;&lt;endl;</p><p><a href="https://codeforces.com/contest/1541/submission/120636509">mysoln</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809119 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809119 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809119"> <li> <div class="comment"> <table class="comment-table" commentId="809124" commentParentId="809119"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809124" href="?#comment-809124" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809119" style="font-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="809124" 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="809124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809124"> <div class="moveup"> <div class="ttypography"><p>My solution is simple. First sort the array. </p><p>Then start connecting adjacent values with their differences. This way sum of all edges with positive weight will be same as the sum of adjacent differences in the array.</p><p>After that start making negative edges for every i. So each i will have i negative edges. Where negative weight is same as -(arr[i] — arr[j]).</p><p>Instead of search it for every j I have formula as (prefixsum till i) — arr[i]*i</p></div> </div> </div> <div class="reply info"> <a class="comment-809124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809124"> <li> <div class="comment"> <table class="comment-table" commentId="809132" commentParentId="809124"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809132" href="?#comment-809132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809124" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809132"> <div class="moveup"> <div class="ttypography"><p>can you tell me why are we sorting the array for a particular node call it x we need to add a negative weight from x to 1 , x to 2 x to 3 till x to x-1 keeping in mind the the path sum doesn't become negative so why are we sorting the array</p></div> </div> </div> <div class="reply info"> <a class="comment-809132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809132"> <li> <div class="comment"> <table class="comment-table" commentId="809135" commentParentId="809132"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809135" href="?#comment-809135" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809135" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809135"> <div class="moveup"> <div class="ttypography"><p>We are sorting values only once so as to connect neighboring nodes with minimum values,i.e. difference b/w consecutive values.<br /> From this sum of positive edges will be minimum.</p></div> </div> </div> <div class="reply info"> <a class="comment-809135 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809135 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809135"> <li> <div class="comment"> <table class="comment-table" commentId="809139" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809139" href="?#comment-809139" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809139" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809139"> <div class="moveup"> <div class="ttypography"><p>ohhh thanks I got it</p></div> </div> </div> <div class="reply info"> <a class="comment-809139 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809139 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809139"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809145" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809145" href="?#comment-809145" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809145" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809145"> <div class="moveup"> <div class="ttypography"><p>My solution is working now I only needed to sort the array my code would have been accepted during the contest :(</p></div> </div> </div> <div class="reply info"> <a class="comment-809145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809145"> </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="809116" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ken_KaNeKi_997" style="position: relative;"> <img src='https://userpic.codeforces.org/1737228/avatar/50ceb845253df5d4.jpg'/> </a> <div><a href="/profile/Ken_KaNeKi_997" title="Newbie Ken_KaNeKi_997" class="rated-user user-gray">Ken_KaNeKi_997</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809116" href="?#comment-809116" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809116" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1737228" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809116"> <div class="moveup"> <div class="ttypography"><p>can anyone explain div2 B plz</p></div> </div> </div> <div class="reply info"> <a class="comment-809116 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809116 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809116"> <li> <div class="comment"> <table class="comment-table" commentId="809204" commentParentId="809116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809204" href="?#comment-809204" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809116" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809204" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809204"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/92199#comment-809178">here</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809204 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809204 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809204"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809122" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809122" href="?#comment-809122" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809122" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809122"> <div class="moveup"> <div class="ttypography"><p>Beautiful Problems. Amazing Round!!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-809122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809122"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809156" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dummybawa" style="position: relative;"> <img src='https://userpic.codeforces.org/1704408/avatar/1522f670cd21321.jpg'/> </a> <div><a href="/profile/dummybawa" title="Expert dummybawa" class="rated-user user-blue">dummybawa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809156" href="?#comment-809156" style="font-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="809156" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809156" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1704408" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809156"> <div class="moveup"> <div class="ttypography"><p>UPD: It's wrong. </p></div> </div> </div> <div class="reply info"> <a class="comment-809156 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809156 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809156"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809178" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809178" href="?#comment-809178" style="font-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="809178" 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="809178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809178"> <div class="moveup"> <div class="ttypography"><p>For DIV 2C/1A can anyone explain with this test case N = 6 and D = 0 1 2 3 2 3. What are the edges that we can have with their weights?</p></div> </div> </div> <div class="reply info"> <a class="comment-809178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809178"> <li> <div class="comment"> <table class="comment-table" commentId="809198" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Zemrith" style="position: relative;"> <img src='https://userpic.codeforces.org/1159882/avatar/2a6566e372882267.jpg'/> </a> <div><a href="/profile/Zemrith" title="Expert Zemrith" class="rated-user user-blue">Zemrith</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809198" href="?#comment-809198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-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="809198" 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="809198" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159882" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809198"> <div class="moveup"> <div class="ttypography"><p>Hello! The answer would be -18.</p><p>Diagram: <img alt=" " src="/predownloaded/8c/88/8c88a0230dea9f499896ee59def659611c605976.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Notice that once you sort the distances, the adjacent nodes have no effect on your final answer. But you can add negative edges as long as they are not adjacent, resulting in such a diagram. Hence you can use prefix sums to solve the problem. (if x nodes came before this, for each node, the answer to add is (x-1)*curr value — csum of first (x-1) nodes). </p><p>Hope that made sense!</p></div> </div> </div> <div class="reply info"> <a class="comment-809198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809198"> <li> <div class="comment"> <table class="comment-table" commentId="809218" commentParentId="809198"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:27">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809218" href="?#comment-809218" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809218" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809218"> <div class="moveup"> <div class="ttypography"><p>Thank you <a class="rated-user user-cyan" href="/profile/Zemrith" title="Специалист Zemrith">Zemrith</a> for so much detail explanation and the solution too it helped me a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-809218 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809218 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809218"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809199" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809199" href="?#comment-809199" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809199" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809199"> <div class="moveup"> <div class="ttypography"><p>first sort the array they will from non negative weight edges. 0 -&gt; 1 -&gt; 2 -&gt; 2 -&gt; 3 -&gt; 3 so the non negative weights will be 1 | 1 | 0 | 1 | 0. form here greedily build most negative weights(backward edges) such that there are no negative cycles.</p></div> </div> </div> <div class="reply info"> <a class="comment-809199 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809199 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809199"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809203" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809203" href="?#comment-809203" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809203" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809203"> <div class="moveup"> <div class="ttypography"><p>First you can sort D and get: <code> N = 6, D = [0, 1, 2, 2, 3, 3] </code></p><p>Now calculate the diffs:</p><p><code>diffs = [1, 1, 0, 1, 0]</code></p><p>The edges for this graph could be something like this:</p> <pre><code> 1 1 0 1 0 &lt;- forward edges 1 &lt;-&gt; 2 &lt;-&gt; 3 &lt;-&gt; 4 &lt;-&gt; 5 &lt;-&gt; 6 -1 -1 0 -1 0 &lt;- backward edges </code></pre><p>Now you have to add more negatives edges, and you could do this by choosing some <code>i</code> and <code>j</code>, <code>i &lt; j</code> and add an edges from <code>j</code> to <code>i</code>, and the weight will be sum of the values from <code>diff[i]</code> to <code>diff[j]</code>.</p><p>Another way to think about this is: look at <code>D</code> array, it represents distances between adjacent nodes, all we have to do is add all of the edges with length 2, then all of the edges of length 3, ..., all of the edges of length <code>N - 1</code>.</p><p>So, for our case we would have these edges</p> <pre><code>a b W ------- 1 2 - 1 2 3 - 1 3 4 - 0 &lt;- adjacent forward edges 4 5 - 1 5 6 - 0 2 1 - -1 3 2 - -1 4 3 - 0 &lt;- adjacent backward edges 5 4 - -1 6 5 - 0 3 1 - -2 4 2 - -1 5 3 - -1 &lt;- edges of length 2 6 4 - -1 4 1 - -2 5 2 - -2 &lt;- edges of length 3 6 3 - -1 5 1 - -3 6 2 - -2 &lt;- edges of length 4 6 1 - -3 &lt;- edges of length 5 </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809203 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809203 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809203"> <li> <div class="comment"> <table class="comment-table" commentId="809221" commentParentId="809203"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809221" href="?#comment-809221" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809203" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809221" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809221"> <div class="moveup"> <div class="ttypography"><p>Thank You <a class="rated-user user-green" href="/profile/ilidar" title="Ученик ilidar">ilidar</a> for clearing my doubt and for detailed explaination.</p></div> </div> </div> <div class="reply info"> <a class="comment-809221 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809221 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809221"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809280" href="?#comment-809280" style="font-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="809280" revisionCount="7" revision="7"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">7</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809280" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+18</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809280"> <div class="moveup"> <div class="ttypography"><p>Could someone please provide a more strict intuition or insight of Div2D/Div1B of why &quot;the actual probability p does not matter&quot;? The intuition in the editorial is still alien to me of why those choices of not progess toward to either stacks (and probability 'p' also changes from time to time too) doesn't matter.</p><p>Update: Here is the intuition I came up with (The strict proof can be found in the comment of the author below)</p><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left) in some states of the current tree.</p><p>now, we will try break this $$$dp_{i,j}$$$ down into the sum of $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$</p><p>We will try to illustrate this with trying to split and color, either red or blue, a stick of length $$$1$$$. The length of the sticks representing the 'probability', and the color of the sticks will represent $$$dp_{i-1,j}$$$(red) or $$$dp_{i,j-1}$$$(blue), depending on the color.</p><p>Suppose in the current state, we have probability $$$p$$$ for choosing to pop each stacks, and the rest $$$1-2p$$$ of doing nothing. The picture will look like this:</p><p><a href="https://ibb.co/q9HjQTm"><img alt="Tree-Array-Rep" border="0" src="/predownloaded/13/57/135732d2b0967af0f76c1dba28df72086f234c7d.png" style="max-width: 100.0%;max-height: 100.0%;" /></a></p><p>We will split the stick equally(*) into several sticks of length $$$p$$$, and then color two of them red and blue. (* We can split it evenly because in the original problem, $$$p$$$ is in the form $$$\frac{1}{number\ of\ candidate\ unmark\ nodes}$$$ ) Now, the remaining sticks represent the state of $$$dp_{i,j}$$$ again (in some other state of the entire tree, so might be in some different $$$p$$$). That means we will split those sticks similary.</p><p>The key observations is:</p><p>1) We know that, in the original problem, if we keep picking nodes that aren't progressing toward the target nodes, we will run out of nodes eventually and finally choose the two nodes. That means, all the sticks will eventually colored into 'red' and 'blue'.</p><p>2) When we split a stick into several smaller equal length sticks, we will color two of them into red and blue. <strong>Those two sticks always have the same length</strong>. That means, the total length of blue sticks and the total length of red sticks will be equal in the end.</p><p>Analogically, that means, eventually, $$$dp_{i,j}$$$ will split into $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$ evenly, no matter $$$p$$$ might be or the state of tree of $$$dp_{i,j}$$$ might be. Therefore, $$$dp_{i,j} = \frac{1}{2} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-809280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809280"> <li> <div class="comment"> <table class="comment-table" commentId="809284" commentParentId="809280"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809284" href="?#comment-809284" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809280" style="font-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="809284" 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="809284" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809284"> <div class="moveup"> <div class="ttypography"><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left), with having arbitary probability $$$0 &lt; p \leq 0.5$$$ of chosing to pick the top of each stack (and $$$1-2p$$$ for doing nothing). Then</p><p>$$$dp_{i,j}=\int_{0}^{0.5} x \cdot (dp_{i-1,j}+dp_{i,j-1}) + (1-2x) \cdot dp_{i,j} \,dx$$$</p><p>Solving the equation, we get $$$dp_{i,j}=\frac{1}{6} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$ What is the mistake in this logic?</p></div> </div> </div> <div class="reply info"> <a class="comment-809284 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809284 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809284"> <li> <div class="comment"> <table class="comment-table" commentId="809399" commentParentId="809284"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809399" href="?#comment-809399" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809284" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809399" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809399"> <div class="moveup"> <div class="ttypography"><p>The biggest issue with this logic is that it's assuming $$$p$$$ is arbitrary chosen from a certain state. While $$$p$$$ can be anything in the world, it is always an exact number from a certain state, hence why an integral is wrong. </p><p>As a different type of intuition, you can think, &quot;is it more likely to reach $$$(i-1, j)$$$ than state $$$(i, j-1)$$$&quot;? and vice versa. For me at least, I don't see how it's possible for either of those questions to be true, so they should be equal.</p><p>If you're looking for a more rigorously correct $$$dp$$$, it would look something like this.</p> <div class="spoiler"><b class="spoiler-title">Proof</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp_{i, j, S}$$$ denote the probability of reaching some node $$$i$$$ distance away before some node $$$j$$$ distance away where $$$S$$$ is a representation of the entire state of of the process (not necessarily an integer). I think you already understood why we can assume the $$$lca$$$ is already reached. We aim to show that $$$S$$$ does not matter in our calculation. Assume inductively that $$$S$$$ does not matter. So, we can assume that states $$$(i-1, j)$$$ and states $$$(i, j-1)$$$ are irrelevant to $$$S$$$. Hence, the part we need to care about is $$$(1-2p) dp_{i, j, S \rightarrow S_a}$$$. A way of thinking about this part of the transition is moving through the collection of $$$S$$$ with the state $$$(i, j)$$$. Obviously, the $$$dp$$$ is a $$$DAG$$$ because no state $$$S$$$ can reach another. Each bounce takes a certain probability $$$p$$$ which is just multiplied in the current path. So, for each state $$$S$$$ with state $$$(i, j)$$$, we have a certain probability to reach it by simply calculating $$$dp$$$ along a DAG as is traditional. Then, from those states of $$$(i, j)$$$ you transition to $$$(i, j-1)$$$ with an equal probability $$$(i-1, j)$$$. So, they have to be equal. Finally, this argument holds for any initial state $$$S$$$ that you reach, so we can conclude that, from any state $$$S$$$ with a state of $$$(i, j)$$$, the probability of transitions to $$$(i-1, j)$$$ and $$$(i, j-1)$$$ are always exactly $$$0.5$$$.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-809399 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809399 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809399"> <li> <div class="comment"> <table class="comment-table" commentId="809701" commentParentId="809399"> <tr> <td class="left"> <div style="position: absolute; left: 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/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809701" href="?#comment-809701" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809399" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809701" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809701"> <div class="moveup"> <div class="ttypography"><p>I see, thank you so much!</p></div> </div> </div> <div class="reply info"> <a class="comment-809701 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809701 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809701"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809298" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/satyam_singh93" style="position: relative;"> <img src='https://userpic.codeforces.org/1763011/avatar/9d9fa405de19ab0e.jpg'/> </a> <div><a href="/profile/satyam_singh93" title="Newbie satyam_singh93" class="rated-user user-gray">satyam_singh93</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809298" href="?#comment-809298" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809298" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1763011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809298"> <div class="moveup"> <div class="ttypography"><p>I am getting wrong ans . could someone tell me where the code make differene ( [yestrday competiton problem .</p><p>`](<a href="https://codeforces.com/contest/1541/problem/B)">https://codeforces.com/contest/1541/problem/B)</a>.</p> <pre><code>int main( ) { clock_t begin = clock(); file_i_o(); // Write your code here.... int t; cin&gt;&gt;t; while(t-- ){ int n; cin&gt;&gt;n; vector&lt;pair&lt;int,int&gt;&gt;v; v.push_back({0,0}); loop(i,0,n) { int x; cin&gt;&gt;x; v.pb({x,i+1}); } sort(v.begin()+1,v.end()); int count =0; for(int i=1 ; i&lt;=n;i++) { for(ll j=i+1;j&lt;=n;j++) { ll left = v[i].first * v[j].first; ll right = v[i].second + v[j].second; if(left == right) count++; if(left &gt; 2*n ) break; } } cout&lt;&lt;count&lt;&lt;endl; } </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809298 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809298 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809298"> <li> <div class="comment"> <table class="comment-table" commentId="809305" commentParentId="809298"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809305" href="?#comment-809305" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809298" style="font-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="809305" 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="809305" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809305"> <div class="moveup"> <div class="ttypography"><p>v[i].first * v[j].first can create overflow. So, you need to convert them to long long by using</p><p>ll left = 1LL * v[i].first * v[j].first;</p><p>instead and it would pass.</p><p>(Simply save the value in long long won't help. You need to convert them to long long before doing multiplication. 1LL* is one way)</p></div> </div> </div> <div class="reply info"> <a class="comment-809305 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809305 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809305"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809309" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809309" href="?#comment-809309" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809309" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809309"> <div class="moveup"> <div class="ttypography"><p>Hi, in problem Div1.B/Div2.D; I can't wrap my head around $$$F[x][y]=F[x−1][y]/2+F[x][y−1]/2$$$. Why is it not $$$F[x][y]=F[x−1][y+1]/2+F[x+1][y−1]/2$$$, can someone please explain to me why is my transition wrong and/or why is the aforementioned transition correct? </p></div> </div> </div> <div class="reply info"> <a class="comment-809309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809309"> <li> <div class="comment"> <table class="comment-table" commentId="809311" commentParentId="809309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809311" href="?#comment-809311" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809311" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809311"> <div class="moveup"> <div class="ttypography"><p>x and y is the distance left for each side right? So, if you take one out, it won't make sense to add that one to the other side since the distance should be either x-1 and y or x and y-1.</p></div> </div> </div> <div class="reply info"> <a class="comment-809311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809311"> <li> <div class="comment"> <table class="comment-table" commentId="809339" commentParentId="809311"> <tr> <td class="left"> <div style="position: absolute; left: 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/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809339" href="?#comment-809339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809339" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809339"> <div class="moveup"> <div class="ttypography"><p>Thank you so much I understand. I had a minor misunderstanding of the parameters to the dp state.</p></div> </div> </div> <div class="reply info"> <a class="comment-809339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809339"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809371" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:13">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809371" href="?#comment-809371" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809371" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809371"> <div class="moveup"> <div class="ttypography"><p>PLease explain why 2 same codes are not giving the same ans</p><p>code forces round 728 div2<br />Problem B :<a href="https://codeforces.com/contest/1541/problem/B">https://codeforces.com/contest/1541/problem/B</a></p><p>AC Submission : <a href="https://ide.codingblocks.com/s/579769">https://ide.codingblocks.com/s/579769</a></p><p>Wrong output Submission :<a href="https://ide.codingblocks.com/s/579771">https://ide.codingblocks.com/s/579771</a></p><p>Difference is using of macro (node) instead of pair&lt;int,int&gt; </p><p>Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-809371 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809371 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809371"> <li> <div class="comment"> <table class="comment-table" commentId="809379" commentParentId="809371"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809379" href="?#comment-809379" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809371" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809379" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809379"> <div class="moveup"> <div class="ttypography"><p>If i am using #define node pair&lt;int,int&gt; it is getting accepted but when i am using typedef pair&lt;int,int&gt; node; it is giving wrong answer</p><p>Why this is happening ?? Is it a bug??</p></div> </div> </div> <div class="reply info"> <a class="comment-809379 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809379 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809379"> <li> <div class="comment"> <table class="comment-table" commentId="809407" commentParentId="809379"> <tr> <td class="left"> <div style="position: absolute; left: 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/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 19:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809407" href="?#comment-809407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809379" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809407" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809407"> <div class="moveup"> <div class="ttypography"><p>Not really sure why this is happening.</p><p>However, I think the problem is the position of #define int long long. So, for #define pair&lt;int,int&gt; node it seems that compiler change node -&gt; pair&lt;int,int&gt; -&gt; pair&lt;long long, long long&gt;. However, when you do typedef, it still keeps in pair&lt;int, int&gt; which creates an overflow problem later on. </p><p>I did try moving #define int long long up above typedef and the code pass. So, my best guess is #define int long long only replace int after that position with long long. Thus, node is still pair&lt;int, int&gt; in the typedef solution, while node is changed to pair&lt;long long, long long&gt; in the second solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-809407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809407"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809627" href="?#comment-809627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809627"> <div class="moveup"> <div class="ttypography"><p>May I ask why in the Div1D solution ci=i-bi, I think it should be ci=bi ...</p></div> </div> </div> <div class="reply info"> <a class="comment-809627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809627"> <li> <div class="comment"> <table class="comment-table" commentId="809631" commentParentId="809627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809631" href="?#comment-809631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809631" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809631"> <div class="moveup"> <div class="ttypography"><p>Check the definition of bi again dude. bi here means <strong>number of elements greater than pi</strong>. So to get ci, which is <strong>number of elements smaller than pi</strong>, you need i-bi.</p></div> </div> </div> <div class="reply info"> <a class="comment-809631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809631"> <li> <div class="comment"> <table class="comment-table" commentId="809636" commentParentId="809631"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809636" href="?#comment-809636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809636"> <div class="moveup"> <div class="ttypography"><p>I read it again. If I read it correctly, bi stands for j&lt;i,pj&gt;pi, and ci stands for j&gt;i,pj&lt;pi. For example, p={1,3,5,4,6,2}, I think b4=1,c4=1, please point out my problem</p></div> </div> </div> <div class="reply info"> <a class="comment-809636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809636"> <li> <div class="comment"> <table class="comment-table" commentId="809638" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809638" href="?#comment-809638" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809638" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809638"> <div class="moveup"> <div class="ttypography"><p>oh, the array index starts from 1</p></div> </div> </div> <div class="reply info"> <a class="comment-809638 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809638 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809638"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809639" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809639" href="?#comment-809639" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809639" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809639"> <div class="moveup"> <div class="ttypography"><p>You are right.</p><p>I guess it might just be typo and ci stands for j&lt;i, pj&lt;pi. At least with this definition of ci the algorithm seems correct :)</p></div> </div> </div> <div class="reply info"> <a class="comment-809639 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809639 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809639"> <li> <div class="comment"> <table class="comment-table" commentId="809641" commentParentId="809639"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809641" href="?#comment-809641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809639" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809641"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-809641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809641"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809705" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/darthrevenge" style="position: relative;"> <img src='https://userpic.codeforces.org/1567000/avatar/ee31d2a91a9575b9.jpg'/> </a> <div><a href="/profile/darthrevenge" title="Candidate Master darthrevenge" class="rated-user user-violet">darthrevenge</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809705" href="?#comment-809705" style="font-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="809705" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809705" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1567000" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809705"> <div class="moveup"> <div class="ttypography"><p>Here's my solution of B div 1 / D div 2 without LCA, using single DFS per node. <a href="/contest/1540/submission/120700765" title="Посылка 120700765 от darthrevenge">120700765</a> It is similar to what <a class="rated-user user-violet" href="/profile/OleschY" title="Кандидат в мастера OleschY">OleschY</a> suggested above. I've tried to describe it in the <a href="https://codeforces.com/blog/entry/92284">blog</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-809705 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809705 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809705"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809951" href="?#comment-809951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809951"> <div class="moveup"> <div class="ttypography"><p>Can someone explain how you can find the LCA for each pair so quick? Iterating through every root is and then considering every pair is already N^3</p></div> </div> </div> <div class="reply info"> <a class="comment-809951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809951"> <li> <div class="comment"> <table class="comment-table" commentId="809965" commentParentId="809951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PurpleCrayon" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809965" href="?#comment-809965" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809965" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="1604355" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809965"> <div class="moveup"> <div class="ttypography"><p>There are a couple ways you could do it:</p> <ol> <li>Just use standard binary lifting (initialize once for each root). This runs in $$$\mathcal{O}(n^3 \log{}n)$$$, and should pass under the given constraints. You could also just use $$$\mathcal{O}(1)$$$ lca using an rmq over an euler tour.</li> <li>You could use a version of dp, where $$$dp[a][b] = lca(a, b)$$$. If the depth of $$$a$$$ is greater than the depth of $$$b$$$, $$$dp[a][b] = dp[parent[a]][b]$$$, otherwise $$$dp[a][b] = dp[a][parent[b]]$$$. The base cases are $$$dp[a][a] = a$$$ for all $$$a$$$. This runs in $$$\mathcal{O}(n^3)$$$.</li> <li>You could extend this idea and do the main solution's dp directly on the tree (without ever worrying about lca's). The recurrence is equivalent to the main solution ($$$dp[a][b] = \frac{dp[parent[a]][b]+dp[a][parent[b]]}{2}$$$ with the base cases being one node is an ancestor of the other.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-809965 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809965 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809965"> <li> <div class="comment"> <table class="comment-table" commentId="809967" commentParentId="809965"> <tr> <td class="left"> <div style="position: absolute; left: 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/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809967" href="?#comment-809967" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809965" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809967" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809967"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the detailed answer!</p></div> </div> </div> <div class="reply info"> <a class="comment-809967 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809967 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809967"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="810320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Anurag_20" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Anurag_20" title="Specialist Anurag_20" class="rated-user user-cyan">Anurag_20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/30/2021 19:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810320" href="?#comment-810320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810320" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1600346" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810320"> <div class="moveup"> <div class="ttypography"><p>O(n2) is also working for div2 C Great Graphs. <a href="https://codeforces.com/contest/1540/submission/120964787">https://codeforces.com/contest/1540/submission/120964787</a></p></div> </div> </div> <div class="reply info"> <a class="comment-810320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810320"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="813828" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/T404" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/T404" title="Master T404" class="rated-user user-orange">T404</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/09/2021 19:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-813828" href="?#comment-813828" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="813828" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="523287" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-813828"> <div class="moveup"> <div class="ttypography"><p>Div1D can be done in $$$O(n \sqrt{n})$$$. We can use square root decomposition to replace all BITs in tutorial. Since a value in a non-updated position changes by at most one and all values change in the same direction, the full recomputation is only needed in the updated position and we can perform an incremental change in $$$O(1)$$$ for values in each non-updated positions.</p><p><a href="https://codeforces.com/contest/1540/submission/121831547">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-813828 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-813828 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-813828"> <li> <div class="comment"> <table class="comment-table" commentId="834051" commentParentId="813828"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KeyID" style="position: relative;"> <img src='https://userpic.codeforces.org/226684/avatar/10e3671716bf6859.jpg'/> </a> <div><a href="/profile/KeyID" title="Grandmaster KeyID" class="rated-user user-red">KeyID</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/29/2021 12:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-834051" href="?#comment-834051" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-813828" style="font-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="834051" 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="834051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="226684" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-834051"> <div class="moveup"> <div class="ttypography"><p>Realy impressive solution. I'm surprised no stars were given to you until me. Maybe many people didn't get your idea since the solution is actually much more complicated than your brief comment(at least in my opinion). I also wrote a piece of code which used your method but simplified a small part of steps. <a href="https://codeforces.com/contest/1540/submission/127317031">Here</a> it is.</p></div> </div> </div> <div class="reply info"> <a class="comment-834051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-834051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-834051"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="837924" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Harolinch" style="position: relative;"> <img src='https://userpic.codeforces.org/427341/avatar/cf8608aeb55edc95.jpg'/> </a> <div><a href="/profile/Harolinch" title="Pupil Harolinch" class="rated-user user-green">Harolinch</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837924" href="?#comment-837924" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837924" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="427341" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837924"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a> in problem Tree array you said that Fixing a given root r, the expected value of the entire process is obviously the sum of the expected values for a fixed root divided by n.</p><p>why we divide by n at the end ? </p></div> </div> </div> <div class="reply info"> <a class="comment-837924 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837924 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837924"> <li> <div class="comment"> <table class="comment-table" commentId="837928" commentParentId="837924"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837928" href="?#comment-837928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-837924" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837928" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837928"> <div class="moveup"> <div class="ttypography"><p>The calculation is independent based on whichever node that you choose first (it becomes the “root”). Initially you choose one of $$$n$$$ nodes with equal probability so you divide by $$$n$$$ at the end after you’ve summed up the independent expected value after choosing the node $$$i$$$ initially.</p></div> </div> </div> <div class="reply info"> <a class="comment-837928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837928"> </ul> </div> </li> </ul> </div> <br/> <div id="editBox-100805" 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 firstPreview100805 = true; var lastPreviewContent100805 = ''; 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=100805] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=100805] 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-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, 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:33:28</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:'81289372dffb0c4e',t:'MTY5NjcwNzIwOC45MzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1540C2
1540
C2
ru
C2. Сходящийся массив (сложная версия)
<div class="problem-statement"><div class="header"><div class="title">C2. Сходящийся массив (сложная версия)</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-bf">Это — усложненная версия задачи. Единственное различие в том, что в данной версии $$$1 \le q \le 10^5$$$. Вы можете взламывать другие решения, только если решены обе версии задачи.</span></p><p>Рассмотрим процесс, проходящий на массивах $$$a$$$ и $$$b$$$ длины $$$n$$$ и $$$n-1$$$ соответственно. </p><p>Процесс — это бесконечная последовательность действий. Каждое действие имеет следующий вид: </p><ul> <li> Сначала, выберем случайное целое число $$$i$$$ ($$$1 \le i \le n-1$$$). </li><li> Теперь, одновременно присвоим $$$a_i = \min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right)$$$ и $$$a_{i+1} = \max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right)$$$ без округлений (то есть значения могут перестать быть целыми). </li></ul> Пример такой операции представлен в заметках.<p>Можно доказать, что массив $$$a$$$ сходится, т. е. для каждого $$$i$$$ существует предел, к которому $$$a_i$$$ сходится. Пусть функция $$$F(a, b)$$$ возвращает значение, к которому сходится $$$a_1$$$, в результате процесса на массивах $$$a$$$ и $$$b$$$.</p><p>Вам задан массив $$$b$$$, но не массив $$$a$$$. Однако вам задан третий массив $$$c$$$. Назовем массив $$$a$$$ хорошим, если он состоит из <span class="tex-font-style-bf">целых чисел</span> и удовлетворяет неравенству $$$0 \leq a_i \leq c_i$$$ для всех $$$1 \leq i \leq n$$$.</p><p>Ваша задача — посчитать количество хороших массивов $$$a$$$, для которых $$$F(a, b) \geq x$$$, для $$$q$$$ значений $$$x$$$. Так как ответ может быть слишком большим, выведите его по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$2 \le n \le 100$$$).</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$c_1, c_2 \ldots, c_n$$$ ($$$0 \le c_i \le 100$$$).</p><p>В третьей строке заданы $$$n-1$$$ целых чисел $$$b_1, b_2, \ldots, b_{n-1}$$$ ($$$0 \le b_i \le 100$$$).</p><p>В четвертой строке задано одно целое число $$$q$$$ ($$$1 \le q \le 10^5$$$).</p><p>В пятой строке заданы $$$q$$$ целых чисел $$$x_1, x_2, \ldots, x_q$$$ ($$$-10^5 \le x_i \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ целых чисел, где $$$i$$$-е число — ответ на $$$i$$$-й запрос, т. е. количество хороших массивов $$$a$$$ с $$$F(a, b) \geq x_i$$$ по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 3 4 2 1 5 -1 0 1 -100000 100000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 56 28 4 60 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Объяснение далее предполагает, что $$$b = [2, 1]$$$ и $$$c=[2, 3, 4]$$$ (как в примере).</p><p>Примеры массивов $$$a$$$, которые <span class="tex-font-style-bf">не</span> являются хорошими: </p><ul> <li> $$$a = [3, 2, 3]$$$ не является хорошим, потому что $$$a_1 &gt; c_1$$$; </li><li> $$$a = [0, -1, 3]$$$ не является хорошим, потому что $$$a_2 &lt; 0$$$. </li></ul><p>Один из возможных хороших массивов $$$a$$$ — это $$$[0, 2, 4]$$$. Можно показать, что ни одна операция его не изменит, а потому $$$F(a, b) = a_1 = 0$$$.</p><p>Другой возможных хороший массив $$$a$$$ — это $$$[0, 1, 4]$$$. За одну операцию с $$$i = 1$$$ мы присваиваем $$$a_1 = \min(\frac{0+1-2}{2}, 0)$$$ и $$$a_2 = \max(\frac{0+1+2}{2}, 1)$$$. То есть, после одной операции с $$$i = 1$$$, $$$a$$$ становится равен $$$[-\frac{1}{2}, \frac{3}{2}, 4]$$$. Можно показать, что далее ни одна операция не изменит массив, а потому $$$F(a, b) = -\frac{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="3bfd68609d50776403bd62ca9123c929"/> <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="Задача - C2 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="73d6e96a98bbd7625389194b3afaf471bd9b24fb"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - C2 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/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='3bfd68609d50776403bd62ca9123c929'>&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%2F1540%2Fproblem%2FC2%3Flocale%3Dru">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='3bfd68609d50776403bd62ca9123c929'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1540">Codeforces Round 728 (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='3bfd68609d50776403bd62ca9123c929'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1540/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='3bfd68609d50776403bd62ca9123c929'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1027089"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3bfd68609d50776403bd62ca9123c929'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1027089"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92093" title="Codeforces Round #728" target="_blank">Codeforces Round #728 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13928" resourceName="Codeforces Round #728" resourceManual="true" src="//codeforces.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/92199" title="Tutorial" target="_blank">Tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13942" 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/1540">Задачи</a></li> <li><a href="/contest/1540/submit">Отослать</a></li> <li><a href="/contest/1540/my">Мои посылки</a></li> <li><a href="/contest/1540/status">Статус</a></li> <li><a href="/contest/1540/hacks">Взломы</a></li> <li><a href="/contest/1540/room/1">Комната</a></li> <li><a href="/contest/1540/standings">Положение</a></li> <li><a href="/contest/1540/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { result.push(c); } } return result.join("").split("\n").map(value => value.trim()).join("\n"); }; </script> <div class="diff-popup"> </div> <div class="problemindexholder" problemindex="C2" data-uuid="ps_f3f909261342a4f457c2b7a59316c752ceedd4bd"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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">C2. Сходящийся массив (сложная версия)</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-bf">Это — усложненная версия задачи. Единственное различие в том, что в данной версии $$$1 \le q \le 10^5$$$. Вы можете взламывать другие решения, только если решены обе версии задачи.</span></p><p>Рассмотрим процесс, проходящий на массивах $$$a$$$ и $$$b$$$ длины $$$n$$$ и $$$n-1$$$ соответственно. </p><p>Процесс — это бесконечная последовательность действий. Каждое действие имеет следующий вид: </p><ul> <li> Сначала, выберем случайное целое число $$$i$$$ ($$$1 \le i \le n-1$$$). </li><li> Теперь, одновременно присвоим $$$a_i = \min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right)$$$ и $$$a_{i+1} = \max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right)$$$ без округлений (то есть значения могут перестать быть целыми). </li></ul> Пример такой операции представлен в заметках.<p>Можно доказать, что массив $$$a$$$ сходится, т. е. для каждого $$$i$$$ существует предел, к которому $$$a_i$$$ сходится. Пусть функция $$$F(a, b)$$$ возвращает значение, к которому сходится $$$a_1$$$, в результате процесса на массивах $$$a$$$ и $$$b$$$.</p><p>Вам задан массив $$$b$$$, но не массив $$$a$$$. Однако вам задан третий массив $$$c$$$. Назовем массив $$$a$$$ хорошим, если он состоит из <span class="tex-font-style-bf">целых чисел</span> и удовлетворяет неравенству $$$0 \leq a_i \leq c_i$$$ для всех $$$1 \leq i \leq n$$$.</p><p>Ваша задача — посчитать количество хороших массивов $$$a$$$, для которых $$$F(a, b) \geq x$$$, для $$$q$$$ значений $$$x$$$. Так как ответ может быть слишком большим, выведите его по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$2 \le n \le 100$$$).</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$c_1, c_2 \ldots, c_n$$$ ($$$0 \le c_i \le 100$$$).</p><p>В третьей строке заданы $$$n-1$$$ целых чисел $$$b_1, b_2, \ldots, b_{n-1}$$$ ($$$0 \le b_i \le 100$$$).</p><p>В четвертой строке задано одно целое число $$$q$$$ ($$$1 \le q \le 10^5$$$).</p><p>В пятой строке заданы $$$q$$$ целых чисел $$$x_1, x_2, \ldots, x_q$$$ ($$$-10^5 \le x_i \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ целых чисел, где $$$i$$$-е число — ответ на $$$i$$$-й запрос, т. е. количество хороших массивов $$$a$$$ с $$$F(a, b) \geq x_i$$$ по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 3 4 2 1 5 -1 0 1 -100000 100000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 56 28 4 60 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Объяснение далее предполагает, что $$$b = [2, 1]$$$ и $$$c=[2, 3, 4]$$$ (как в примере).</p><p>Примеры массивов $$$a$$$, которые <span class="tex-font-style-bf">не</span> являются хорошими: </p><ul> <li> $$$a = [3, 2, 3]$$$ не является хорошим, потому что $$$a_1 &gt; c_1$$$; </li><li> $$$a = [0, -1, 3]$$$ не является хорошим, потому что $$$a_2 &lt; 0$$$. </li></ul><p>Один из возможных хороших массивов $$$a$$$ — это $$$[0, 2, 4]$$$. Можно показать, что ни одна операция его не изменит, а потому $$$F(a, b) = a_1 = 0$$$.</p><p>Другой возможных хороший массив $$$a$$$ — это $$$[0, 1, 4]$$$. За одну операцию с $$$i = 1$$$ мы присваиваем $$$a_1 = \min(\frac{0+1-2}{2}, 0)$$$ и $$$a_2 = \max(\frac{0+1+2}{2}, 1)$$$. То есть, после одной операции с $$$i = 1$$$, $$$a$$$ становится равен $$$[-\frac{1}{2}, \frac{3}{2}, 4]$$$. Можно показать, что далее ни одна операция не изменит массив, а потому $$$F(a, b) = -\frac{1}{2}$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C2]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c6d7c9759d76',t:'MTY5NjY2NzM3MC4zMzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*2900"]
https://codeforces.com/blog/entry/92199
<!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="ea33d124a1ff874ace73f937748d303e"/> <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="Codeforces Round #728 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #728 Editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='ea33d124a1ff874ace73f937748d303e'>&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%2F92199">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='ea33d124a1ff874ace73f937748d303e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:31:32</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:31:32</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='ea33d124a1ff874ace73f937748d303e'/> <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/PurpleCrayon">PurpleCrayon</a></li> <li class="current selectedLava"><a href="/blog/PurpleCrayon">Blog</a></li> <li><a href="/teams/with/PurpleCrayon">Teams</a></li> <li><a href="/submissions/PurpleCrayon">Submissions</a></li> <li><a href="/groups/with/PurpleCrayon">Groups</a></li> <li><a href="/contests/with/PurpleCrayon">Contests</a></li> <li><a href="/contests/writer/PurpleCrayon">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/PurpleCrayon" style="text-decoration:none;color:black !important;">PurpleCrayon's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="92809"> <div class="title"> <a href="/blog/entry/92199"> <p>Codeforces Round #728 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a>, <a href="/topic/92809/en10">history</a>, <span class="format-humantime" title="Jun/25/2021 20:44">2 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><a href="/contest/1541/problem/A" title="Codeforces Round 728 (Div. 2)">1541A - Pretty Permutations</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The parity (whether $$$n$$$ is odd or even) matters.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Swapping two adjacent cats keeps both of them close to their original location and changes both of their locations.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>If $$$n$$$ is even, the optimal distance is $$$n$$$, and if $$$n$$$ is odd the optimal distance is $$$n+1$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541A">Tutorial is loading...</div></div></div><p><a href="/contest/1541/problem/B" title="Codeforces Round 728 (Div. 2)">1541B - Pleasant Pairs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>$$$i+j \leq 2 \cdot n$$$</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The number of pairs $$$(a, b)$$$ such that $$$a \cdot b \leq x$$$ is $$$O(x log x)$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/A" title="Codeforces Round 728 (Div. 1)">1540A - Great Graphs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What's the minimum value that an edge from $$$a$$$ to $$$b$$$ can be?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use edges with negative value whenever you can.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The sum of the values of edges with positive weight must be $$$\geq$$$ the maximum value in the array.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540A">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Tree Array</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Fix the initial node chosen and root the tree there, what is the contribution of each pair of nodes?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Nothing matters besides the path from node $$$a$$$ to node $$$b$$$, and the initially chosen node $$$r$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>You are given two stacks of size $$$a_1$$$ and $$$a_2$$$. In a single step, you randomly choose a stack to remove a single item from. What is the probability that $$$a_1$$$ becomes $$$0$$$ before $$$a_2$$$? Can you extend this argument for an arbitrary probability $$$p$$$ to remove from one of the two stacks, and a probability of $$$1-2p$$$ to do nothing?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/C2" title="Codeforces Round 728 (Div. 1)">1540C2 - Converging Array (Hard Version)</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What are the invariants? The monovariants?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What is the prefix sum array of the converged array? What is the difference array of the converged array?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you conducted the process on a prefix of size $$$1$$$, then of size $$$2$$$, and on and on?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How many values $$$x$$$ are actually interesting?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540C2">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Inverse Inversions</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The answer is always unique.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Try to figure out what the location of the $$$i$$$-th element would be if you only looked at the first $$$i$$$ elements, then the first $$$i+1$$$, etc. to find an $$$O(nq)$$$ solution.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use sqrt decomposition to optimize it.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540D">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/E" title="Codeforces Round 728 (Div. 1)">1540E - Tasty Dishes</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How much does each chef's initial dish contribute at time $$$k$$$?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you really, really wanted to use matrix exponentiation?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How can you multiply some vectors by a matrix in $$$O(N)$$$ time? (go back to linear algebra class)</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Decompose into linear combinations of eigenvectors.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540E">Tutorial is loading...</div></div></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/1540" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 1)</a> </span> </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/1541" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-191295-92809").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "191295", blogEntryId: "92199", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-92809"><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'>+96</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-92809"><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/PurpleCrayon"><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/PurpleCrayon"> PurpleCrayon </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="Jun/25/2021 20:44">2 years ago</span> </li> <li> <a href="/blog/entry/92199#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/92199#comments"> 170 </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="100805"> <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 (136)</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="808750" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808750" href="?#comment-808750" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808750" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-66" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-66</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808750"> <div class="moveup"> <div class="ttypography"><p>PURPLECRAYON ORZ</p></div> </div> </div> <div class="reply info"> <a class="comment-808750 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808750 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808750"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808751" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hbarp" style="position: relative;"> <img src='https://userpic.codeforces.org/1387715/avatar/c727a810db6ffb66.jpg'/> </a> <div><a href="/profile/hbarp" title="Candidate Master hbarp" class="rated-user user-violet">hbarp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808751" href="?#comment-808751" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808751" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="1387715" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-83</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808751"> <div class="moveup"> <div class="ttypography"><p>Damn, so orz round. <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Мастер PurpleCrayon">PurpleCrayon</a> orz</p></div> </div> </div> <div class="reply info"> <a class="comment-808751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808751"> <li> <div class="comment"> <table class="comment-table" commentId="808805" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/naman1601" style="position: relative;"> <img src='https://userpic.codeforces.org/1703219/avatar/d63fc523dc05fda8.jpg'/> </a> <div><a href="/profile/naman1601" title="Master naman1601" class="rated-user user-orange">naman1601</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808805" href="?#comment-808805" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808805" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-51" data-commentUserId="1703219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-51</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808805"> <div class="moveup"> <div class="ttypography"><p>yeah, amazing problemset, not speedforces at all :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808805 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808805 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808805"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808817" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LOVELY_BOY_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/LOVELY_BOY_" title="Newbie LOVELY_BOY_" class="rated-user user-gray">LOVELY_BOY_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808817" href="?#comment-808817" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-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="808817" 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="808817" class="CommentVoteFrame" data-commentRating="35" data-commentUserId="2089809" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808817"> <div class="moveup"> <div class="ttypography"><p>LOL <a class="rated-user user-blue" href="/profile/hbarp" title="Эксперт hbarp">hbarp</a>,even you didn't participate in the contest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808817 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808817 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808817"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808753" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DontLookBack" style="position: relative;"> <img src='https://userpic.codeforces.org/1534766/avatar/4eacdc5f9758fc28.jpg'/> </a> <div><a href="/profile/DontLookBack" title="Specialist DontLookBack" class="rated-user user-cyan">DontLookBack</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808753" href="?#comment-808753" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808753" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1534766" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808753"> <div class="moveup"> <div class="ttypography"><p>I am curious, how many div2 testers solved D?</p></div> </div> </div> <div class="reply info"> <a class="comment-808753 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808753 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808753"> <li> <div class="comment"> <table class="comment-table" commentId="808826" commentParentId="808753"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/highonjuice" style="position: relative;"> <img src='https://userpic.codeforces.org/1457566/avatar/f7988dd2af03d38b.jpg'/> </a> <div><a href="/profile/highonjuice" title="Pupil highonjuice" class="rated-user user-green">highonjuice</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808826" href="?#comment-808826" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808753" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808826" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1457566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808826"> <div class="moveup"> <div class="ttypography"><p>like 2 ppl, it was hard for me</p></div> </div> </div> <div class="reply info"> <a class="comment-808826 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808826 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808826"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808757" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tlatoani" style="position: relative;"> <img src='https://userpic.codeforces.org/614001/avatar/598b4e8358aad1b4.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/Tlatoani" title="Grandmaster Tlatoani" class="rated-user user-red">Tlatoani</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:18">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808757" href="?#comment-808757" style="font-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="808757" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="808757" class="CommentVoteFrame" data-commentRating="121" data-commentUserId="614001" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+121</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808757"> <div class="moveup"> <div class="ttypography"><h4>Alternate solution to <a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Инвертируем инверсии</a></h4><p>(Read the first nontrivial paragraph of the editorial before reading this alternate solution)</p><p>Let $$$p_r(k) = x$$$ denote that of the numbers $$$p(1), \ldots, p(r)$$$ in sorted order, $$$p(k)$$$ is equal to the $$$x$$$th of these numbers. We will take a decomposition strategy just as the editorial does, though our strategy will be different. We will divide $$$[1, n]$$$ into blocks of length $$$b$$$. For each block covering some interval $$$[l, r]$$$, we will store $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>This means that for any $$$k$$$, if we know $$$p_r(k)$$$ for some block $$$[l, r]$$$, then we can determine $$$p_{r'}(k)$$$ for the block $$$[l', r']$$$ immediately to the right by binary searching on the numbers stored for $$$[l', r']$$$. Therefore, we can perform queries in $$$O\left(\frac n b \lg b\right)$$$.</p><p>We now need to figure out updates. There are probably simple ways to perform updates in $$$O(b\lg b)$$$, but this yields an overall runtime of $$$O(q\sqrt n \lg n)$$$ which is too slow.</p><p>Therefore, we can instead store each block as a segment tree. For each range $$$[l, r]$$$ in the segment tree we store the same thing we store for the whole block: $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>We then have to quickly merge two intervals. We can merge two intervals of length $$$\lambda$$$ in $$$O(\lambda \lg \lambda)$$$ by doing binary search just as we did above, but this still only yields $$$O(b\lg b)$$$ update overall. However, these $$$\lambda$$$ binary searches can be optimized using two pointers to $$$O(\lambda)$$$, making the overall update $$$O(b)$$$.</p><p>We thus have $$$O\left(\frac n b \lg b\right)$$$ query and $$$O(b)$$$ update. Therefore, we can choose $$$b = \sqrt{n\lg n}$$$ to attain an overall runtime of $$$O\left(q\sqrt{n\lg n}\right)$$$ just as the editorial does.</p><p><a href="https://codeforces.com/contest/1540/submission/120611645">Submission in Kotlin</a></p><p><a href="https://codeforces.com/contest/1540/submission/120612729">Submission in C++</a></p><p>It is interesting to note that this solution is quite fast. At the time of writing this update, the C++ version is the fastest correct submission (and runs under 1 second!) and the Kotlin version is faster than the vast majority of submissions.</p></div> </div> </div> <div class="reply info"> <a class="comment-808757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808757"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808765" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardcode229" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardcode229" title="Newbie hardcode229" class="rated-user user-gray">hardcode229</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808765" href="?#comment-808765" style="font-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="808765" 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="808765" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1635180" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808765"> <div class="moveup"> <div class="ttypography"><p>The 3rd hint for the second problem is same as that of the first problem, is it related or a mistake? <strong>UPD:</strong> it is corrected.</p></div> </div> </div> <div class="reply info"> <a class="comment-808765 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808765 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808765"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808769" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/peanut" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/peanut" title="Specialist peanut" class="rated-user user-cyan">peanut</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:24">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808769" href="?#comment-808769" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808769" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="1167233" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+22</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808769"> <div class="moveup"> <div class="ttypography"><p>speedforces.</p></div> </div> </div> <div class="reply info"> <a class="comment-808769 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808769 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808769"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808781" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/graphs_11" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/graphs_11" title="Specialist graphs_11" class="rated-user user-cyan">graphs_11</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808781" href="?#comment-808781" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808781" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1610110" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808781"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">Problem B Detailed Explanation</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808781 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808781 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808781"> <li> <div class="comment"> <table class="comment-table" commentId="809069" commentParentId="808781"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:40">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809069" href="?#comment-809069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808781" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809069" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809069"> <div class="moveup"> <div class="ttypography"><p>Thank you, very well explained</p></div> </div> </div> <div class="reply info"> <a class="comment-809069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809069"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808790" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PC_E1052" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PC_E1052" title="Pupil PC_E1052" class="rated-user user-green">PC_E1052</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808790" href="?#comment-808790" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808790" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="811219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808790"> <div class="moveup"> <div class="ttypography"><p>c was too easy, d was too hard. but d was very nice problem though. </p></div> </div> </div> <div class="reply info"> <a class="comment-808790 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808790 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808790"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808793" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808793" href="?#comment-808793" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808793" class="CommentVoteFrame" data-commentRating="58" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+58</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808793"> <div class="moveup"> <div class="ttypography"><p>Paging <a class="rated-user user-legendary" href="/profile/ecnerwala" title="Легендарный гроссмейстер ecnerwala"><span class="legendary-user-first-letter">e</span>cnerwala</a> to explain his solution to D1E if he'd like. It seems offline?</p></div> </div> </div> <div class="reply info"> <a class="comment-808793 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808793 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808793"> <li> <div class="comment"> <table class="comment-table" commentId="808979" commentParentId="808793"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ecnerwala" 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/ecnerwala" title="Legendary Grandmaster ecnerwala" class="rated-user user-legendary"><span class="legendary-user-first-letter">e</span>cnerwala</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808979" href="?#comment-808979" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808793" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808979" class="CommentVoteFrame" data-commentRating="40" data-commentUserId="57502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808979"> <div class="moveup"> <div class="ttypography"><p>My solution is $$$O(K N^3 + QN)$$$. I just precomputed the coefficient of each $$$a_i$$$ for each prefix-range for each number of days since person $$$i$$$ becomes positive (only $$$1000$$$ possible days) in $$$O(N \cdot K \cdot N^2)$$$, and then summed up the appropriate ones to answer each query in $$$O(N)$$$. It's written in the offline style to use only $$$O(KN)$$$ memory at a time (grouped by $$$a_i$$$) instead of $$$O(KN^2)$$$.</p><p>My passing submission is just $$$KN^3 / 6$$$ instead of the $$$KN^3$$$ I submitted in contest :'(</p><p>If you guys wanted to prevent this, $$$K$$$ could've been much higher, like $$$1e18$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808979 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808979 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808979"> <li> <div class="comment"> <table class="comment-table" commentId="809002" commentParentId="808979"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809002" href="?#comment-809002" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808979" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809002" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809002"> <div class="moveup"> <div class="ttypography"><p>:( I knew of this solution (it’s why ML is tight) but I didn’t realize that it could be done offline with small memory. Of course $$$K$$$ higher is obvious solution but main issue is that the extra modulos from binary exponentiation make it very hard to pass in Java without allowing other unoptimal solutions through such as precomputing inverses of the matrix. Probably $$$k=10^5$$$ would’ve been a better choice. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-809002 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809002 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809002"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808795" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zukonit14" style="position: relative;"> <img src='https://userpic.codeforces.org/1192187/avatar/5afd49be87fb87d9.jpg'/> </a> <div><a href="/profile/zukonit14" title="Expert zukonit14" class="rated-user user-blue">zukonit14</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808795" href="?#comment-808795" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808795" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1192187" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808795"> <div class="moveup"> <div class="ttypography"><p>Does Div2 D deserved to be D Problem? According to me it should've been Div2 E.</p></div> </div> </div> <div class="reply info"> <a class="comment-808795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808795"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808796" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mangat_angad" style="position: relative;"> <img src='https://userpic.codeforces.org/1449578/avatar/d3cadb0c26e0c11f.jpg'/> </a> <div><a href="/profile/mangat_angad" title="Specialist mangat_angad" class="rated-user user-cyan">mangat_angad</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808796" href="?#comment-808796" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808796" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1449578" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808796"> <div class="moveup"> <div class="ttypography"><p>I feel like such an idiot for not being able to understand problem C (Div2). For some reason I thought the nodes were connected like this — 1-&gt;2-&gt;3-&gt;....-&gt;N and that we had to minimise answer by adding other edges (of negative weight in case they dont give a negative cycle) to this graph.</p></div> </div> </div> <div class="reply info"> <a class="comment-808796 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808796 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808796"> <li> <div class="comment"> <table class="comment-table" commentId="808896" commentParentId="808796"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808896" href="?#comment-808896" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808796" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808896" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808896"> <div class="moveup"> <div class="ttypography"><p>But that's exactly what I did, and the final answer is the sum of the array — sum of all subarrays. <a href="https://codeforces.com/contest/1541/submission/120611950">120611950</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808896 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808896 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808896"> <li> <div class="comment"> <table class="comment-table" commentId="808941" commentParentId="808896"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808941" href="?#comment-808941" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808896" style="font-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="808941" 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="808941" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808941"> <div class="moveup"> <div class="ttypography"><p>No, that's not what you did. To compute the answer via the method described above, you would have to compute how many elements are lesser than the current element at any given iteration and add them and also keep and their count using a Fenwick tree/ BIT. That's the incorrect approach though because sorting would be more optimal.</p></div> </div> </div> <div class="reply info"> <a class="comment-808941 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808941 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808941"> <li> <div class="comment"> <table class="comment-table" commentId="808952" commentParentId="808941"> <tr> <td class="left"> <div style="position: absolute; left: 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/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808952" href="?#comment-808952" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808941" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808952" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808952"> <div class="moveup"> <div class="ttypography"><p>Sorry if I misunderstood things. mangat_angad only mentioned adding negative weighed edges to the 1-&gt;2-&gt;3-&gt;...N graph, which is what I thought to arrive at my solution. The array I mentioned is indeed sorted and formed by distance differences which are the weights in the 1-&gt;2-&gt;3-&gt;...N graph. Unfortunately I'm still too noob to understand the tree structures you mentioned.</p></div> </div> </div> <div class="reply info"> <a class="comment-808952 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808952 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808952"> <li> <div class="comment"> <table class="comment-table" commentId="808955" commentParentId="808952"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808955" href="?#comment-808955" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808952" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808955" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808955"> <div class="moveup"> <div class="ttypography"><p>Nothing unfortunate about it, logic trumps everything </p></div> </div> </div> <div class="reply info"> <a class="comment-808955 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808955 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808955"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808797" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808797" href="?#comment-808797" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808797" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808797"> <div class="moveup"> <div class="ttypography"><p>Just want to apologize to authors for the stupidest question, I misread the task..</p></div> </div> </div> <div class="reply info"> <a class="comment-808797 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808797 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808797"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808813" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808813" href="?#comment-808813" style="font-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="808813" 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="808813" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808813"> <div class="moveup"> <div class="ttypography"><p>Can someone tell me the meaning of this line in problem Div2D/Div1B<br /></p> <blockquote><p>Note that, until reaching, l every possible process still has the same probability of reaching b before a. Therefore, we can assume that the process has reached l and calculate the probability from there.</p> </blockquote><p>What same probability are they talking about?</p></div> </div> </div> <div class="reply info"> <a class="comment-808813 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808813 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808813"> <li> <div class="comment"> <table class="comment-table" commentId="808831" commentParentId="808813"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808831" href="?#comment-808831" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808813" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808831" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808831"> <div class="moveup"> <div class="ttypography"><p>Here's what it's trying to say:</p><p>Suppose we start by marking the root. To mark a or b, we must first mark the lca, so we may assume that the lca has just been marked.</p></div> </div> </div> <div class="reply info"> <a class="comment-808831 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808831 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808831"> <li> <div class="comment"> <table class="comment-table" commentId="808840" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808840" href="?#comment-808840" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808840" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808840"> <div class="moveup"> <div class="ttypography"><p>And what does this line mean? <em>&quot;The problem can be rephrased as having two stacks of size dist(l,a) and dist(l,b) with an arbitrary p to remove a node from one of the two stack (and 1−2p to nothing) and finding the probability that dist(l,b) reaches zero before dist(l,a).&quot;</em></p></div> </div> </div> <div class="reply info"> <a class="comment-808840 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808840 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808840"> <li> <div class="comment"> <table class="comment-table" commentId="808857" commentParentId="808840"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808857" href="?#comment-808857" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808840" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808857" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808857"> <div class="moveup"> <div class="ttypography"><p>Once you've reached the lca $$$l$$$, in a single step you either step closer to $$$a$$$, step closer to $$$b$$$, or step closer to neither.</p></div> </div> </div> <div class="reply info"> <a class="comment-808857 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808857 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808857"> <li> <div class="comment"> <table class="comment-table" commentId="808862" commentParentId="808857"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808862" href="?#comment-808862" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808857" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808862" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808862"> <div class="moveup"> <div class="ttypography"><p>Can you add implementation for this problem please?</p></div> </div> </div> <div class="reply info"> <a class="comment-808862 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808862 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808862"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808849" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808849" href="?#comment-808849" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808849" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808849"> <div class="moveup"> <div class="ttypography"><p>So, we mark lca first (of course). But why wouldn't it affect the final probability of reaching b before a? I mean, why is it sufficient to calculate the probability after marking lca?</p></div> </div> </div> <div class="reply info"> <a class="comment-808849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808849"> <li> <div class="comment"> <table class="comment-table" commentId="808873" commentParentId="808849"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808873" href="?#comment-808873" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808849" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808873" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808873"> <div class="moveup"> <div class="ttypography"><p>Before marking the lca, there is no way to make more progress towards $$$b$$$ than $$$a$$$ or vice versa. The subset of marked vertices also does not change the probability of moving towards $$$a$$$ or $$$b$$$ after reaching the lca because we're choosing uniformly at random and exactly two vertices are of interest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808873 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808873 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808873"> <li> <div class="comment"> <table class="comment-table" commentId="808883" commentParentId="808873"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808883" href="?#comment-808883" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808873" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808883" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808883"> <div class="moveup"> <div class="ttypography"><p>Now I get it. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808883 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808883 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808883"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808814" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808814" href="?#comment-808814" style="font-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="808814" 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="808814" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808814"> <div class="moveup"> <div class="ttypography"><p>So, my Solution for <strong>Div1 Problem B</strong> / <strong>Div2 Problem D</strong> / <strong>1540B — Tree Array</strong>:</p><p>Chose two Nodes $$$A$$$ and $$$B$$$ with $$$A&gt;B$$$. </p><p><strong>First DFS:</strong> Find the path from $$$A$$$ to $$$B$$$. I call it $$$path_p$$$. On $$$path_p$$$ mark the distance to $$$B$$$ for each node. </p><p><strong>Second DFS:</strong> For each remaining node $$$N$$$ find the shortest path to $$$path_p$$$. It will hit it at some node of the $$$path_p$$$ which has some distance $$$D$$$ marked on it. We mark $$$N$$$ with $$$D$$$. (See comment below for image.)</p><p><strong>Calculation:</strong> For each node $$$N$$$ we can calculate $$$P_i$$$. $$$P_i$$$ is the probability to reach Node $$$B$$$ before we reach Node $$$A$$$. We sum $$$P_i$$$ for each node. $$$P_i$$$ is also the probability, that the pair of Nodes $$$A$$$ and $$$B$$$ with starting node $$$N$$$ will contribute to the inversion sum. </p><p><strong>Iteration:</strong> We need to repeat this for each pair $$$A$$$ and $$$B$$$. In the end we divide the answer by $$$n$$$, the amount of nodes (the probability to start with Node $$$N$$$). </p><p>This algorithm is $$$O(N^3)$$$. See my Solution <a href="/contest/1540/submission/120603369" title="Посылка 120603369 от OleschY">120603369</a></p> <div class="spoiler"><b class="spoiler-title">How to calculate P_i</b><div class="spoiler-content" style="display: none;"><p>I wrote myself a small helper DP-program to find the regularities. Let $$$D$$$ be the Distance between $$$A$$$ and $$$B$$$ and $$$d$$$ be the distance from the node $$$N$$$ to $$$B$$$. My educated guess was: $$$P_i=\frac{\sum_{i=0}^{d-1}\binom{D-1}{i} }{2^{D-1}}$$$</p> <div class="spoiler"><b class="spoiler-title">Helper Program</b><div class="spoiler-content" style="display: none;"><p>It checks for a path of some length for each Intervall $$$[A,B]$$$ which is already visited, what the probability to reach one node before the other is. </p> <pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; int solve(int n) { vector&lt;vector&lt;double&gt;&gt; dp(n, vector&lt;double&gt;(n, 0)); for(int i = 0; i &lt; n; ++i) { dp[0][i] = 1; dp[i][n - 1] = 0; } dp[0][n - 1] = -1; for(int w = n; w &gt;= 0; w--) { for(int i = 1; i + w &lt; n - 1; i++) { int l = i; int r = w + i; dp[l][r] = 0.5 * (dp[l - 1][r] + dp[l][r + 1]); } } cout &lt;&lt; n &lt;&lt; &quot;\n\n&quot;; for(int i = 0; i &lt; n; i++) { cout &lt;&lt; dp[i][i]*(1&lt;&lt;(n-2)) &lt;&lt; &quot;\n&quot;; } cout &lt;&lt; &quot;\n\n\n\n&quot;; return 0; } //====================== // Technical stuff //====================== int main() { int ntest = 12; for(int test = 2; test &lt; ntest; ++test) { solve(test); } return 0; } </code></pre></div></div></div></div></div> </div> </div> <div class="reply info"> <a class="comment-808814 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808814 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808814"> <li> <div class="comment"> <table class="comment-table" commentId="808843" commentParentId="808814"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808843" href="?#comment-808843" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808814" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808843" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808843"> <div class="moveup"> <div class="ttypography"><p>Can you explain your solution in a little bit more detail? :')</p></div> </div> </div> <div class="reply info"> <a class="comment-808843 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808843 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808843"> <li> <div class="comment"> <table class="comment-table" commentId="808869" commentParentId="808843"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808869" href="?#comment-808869" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808843" style="font-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="808869" 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="808869" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808869"> <div class="moveup"> <div class="ttypography"><p>Oof, I can give you an image, that shows how the distances from the two DFS are distributed on an example. You can see Nodes $$$A$$$ and $$$B$$$ and the numbers are the distances we write into the nodes. </p><p><img alt=" " src="/predownloaded/d8/2f/d82f98ecd2c1b4bd15b3c40e62476f6ae2741a64.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>If you have specific questions about some steps go ahead and ask. </p></div> </div> </div> <div class="reply info"> <a class="comment-808869 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808869 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808869"> <li> <div class="comment"> <table class="comment-table" commentId="810069" commentParentId="808869"> <tr> <td class="left"> <div style="position: absolute; left: 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/Mrajaryan" style="position: relative;"> <img src='https://userpic.codeforces.org/1377953/avatar/e904b3a3a2eac1ad.jpg'/> </a> <div><a href="/profile/Mrajaryan" title="Newbie Mrajaryan" class="rated-user user-gray">Mrajaryan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 15:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810069" href="?#comment-810069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808869" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810069" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1377953" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810069"> <div class="moveup"> <div class="ttypography"><p>what does the dp states mean in your helper program? I am unable to understand. Can you please explain?</p></div> </div> </div> <div class="reply info"> <a class="comment-810069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810069"> <li> <div class="comment"> <table class="comment-table" commentId="810097" commentParentId="810069"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 18:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810097" href="?#comment-810097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-810069" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810097"> <div class="moveup"> <div class="ttypography"><p>You have Nodes $$$1$$$ through $$$N$$$, neighbouring IDs are connected. The state $$$dp[l][r]$$$ is the probability, that node $$$N$$$ will be reached before node $$$1$$$ with all the nodes $$$l$$$ through $$$r$$$ marked already. Obviously $$$dp[1][x]=0$$$ and $$$dp[x][N]=1$$$ ($$$dp[1][N]$$$ can't happen). The recurrence is $$$dp[l][r]=(dp[l-1][r]+dp[l][r+1])/2$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-810097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808818" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808818" href="?#comment-808818" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808818" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808818"> <div class="moveup"> <div class="ttypography"><p>I can't grasp the editorial of Div 2 D/ Div 1 B. Can somebody provide a more intuitive explanation?</p></div> </div> </div> <div class="reply info"> <a class="comment-808818 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808818 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808818"> <li> <div class="comment"> <table class="comment-table" commentId="808821" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:45">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808821" href="?#comment-808821" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808821" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808821"> <div class="moveup"> <div class="ttypography"><p>same :(</p></div> </div> </div> <div class="reply info"> <a class="comment-808821 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808821 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808821"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808861" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808861" href="?#comment-808861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808861" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808861"> <div class="moveup"> <div class="ttypography"><p>Step 1. use linearity of expectation. The answer is</p> <center>$$$\sum_{a&lt;b} P(b\text{ appears before }a). $$$</center><p>Step 2: Observe that if we start by marking a vertex $$$c$$$ on the path between $$$a$$$ and $$$b$$$, and suppose the next marked vertex on the path is $$$d$$$. Then, the probability that $$$d$$$ is between $$$c$$$ and $$$a$$$ and the probability that $$$d$$$ is between $$$c$$$ and $$$b$$$ are both $$$1/2$$$. This is because there are only two choices for $$$d$$$ and we're choosing uniformly at random. This means that the answer only depends on $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p><p>Step 3: run a dp to calculate the probability that we mark $$$b$$$ before $$$a$$$ given $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808861"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808833" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808833" href="?#comment-808833" style="font-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="808833" 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="808833" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-72" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-72</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808833"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin &gt;&gt; t; while(t--){ int n; cin &gt;&gt; n; long long arr[n]; for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0; for(int i = 0; i &lt; n — 1; i++){ for(int j = arr[i] — 2 — i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } } } cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;; } return 0; }</p><p>/* Accepted code A different approach using arrays (as I don't know what vectors are, haven't read that) I hope this is a optimal approach. Any suggestions related to this are whole-heartedly welcomed. Also, please guide me how could I have optimized the code to a much extent. Thanks in advance! Keep programming! */</p></div> </div> </div> <div class="reply info"> <a class="comment-808833 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808833 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808833"> <li> <div class="comment"> <table class="comment-table" commentId="808844" commentParentId="808833"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808844" href="?#comment-808844" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808833" style="font-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="808844" 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="808844" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-35" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808844"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-808844 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808844 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808844"> <li> <div class="comment"> <table class="comment-table" commentId="808863" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808863" href="?#comment-808863" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808863" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808863"> <div class="moveup"> <div class="ttypography"><p>Not studied yet, I'm still a beginner, but planning to start soon. Thanks for the guidance.</p></div> </div> </div> <div class="reply info"> <a class="comment-808863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808863"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808879" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808879" href="?#comment-808879" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808879" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808879"> <div class="moveup"> <div class="ttypography"><p>once upon a time, I also did problems while not know what vectors are. sad times :'(</p></div> </div> </div> <div class="reply info"> <a class="comment-808879 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808879 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808879"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808926" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808926" href="?#comment-808926" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808926" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808926"> <div class="moveup"> <div class="ttypography"><p>There's no issue in not knowing vectors. Yes they are important I agree but not knowing vectors should not be discouraged. I became expert here without knowing anything about vectors plus he is a beginner so he shouldn't be discouraged like this.</p></div> </div> </div> <div class="reply info"> <a class="comment-808926 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808926 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808926"> <li> <div class="comment"> <table class="comment-table" commentId="808927" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Tech.Maniac" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Tech.Maniac" title="Expert Tech.Maniac" class="rated-user user-blue">Tech.Maniac</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808927" href="?#comment-808927" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808927" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1242860" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808927"> <div class="moveup"> <div class="ttypography"><p>+1, I agree with you. Same I was expert last year solely using arrays</p></div> </div> </div> <div class="reply info"> <a class="comment-808927 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808927 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808927"> <li> <div class="comment"> <table class="comment-table" commentId="809201" commentParentId="808927"> <tr> <td class="left"> <div style="position: absolute; left: 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/Yash.Amin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Yash.Amin" title="Specialist Yash.Amin" class="rated-user user-cyan">Yash.Amin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809201" href="?#comment-809201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808927" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809201" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-28" data-commentUserId="1226462" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-28</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809201"> <div class="moveup"> <div class="ttypography"><p>Bas kar bsdk kitna jhooth bolega</p></div> </div> </div> <div class="reply info"> <a class="comment-809201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809201"> <li> <div class="comment"> <table class="comment-table" commentId="809215" commentParentId="809201"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809215" href="?#comment-809215" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809215" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809215"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-blue" href="/profile/Yash.Amin" title="Эксперт Yash.Amin">Yash.Amin</a> Could you please refrain from using foul language on educational discussions. Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-809215 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809215 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809215"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808928" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808928" href="?#comment-808928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808928" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808928"> <div class="moveup"> <div class="ttypography"><p>Ah my bad, I did not want to come across as being arrogant, but I was genuinely confused that some people did not know vectors although they are using C++.</p></div> </div> </div> <div class="reply info"> <a class="comment-808928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808928"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808839" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamkiller04" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dreamkiller04" title="Newbie dreamkiller04" class="rated-user user-gray">dreamkiller04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808839" href="?#comment-808839" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2089608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808839"> <div class="moveup"> <div class="ttypography"><p>Please add implementations too.</p></div> </div> </div> <div class="reply info"> <a class="comment-808839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808839"> <li> <div class="comment"> <table class="comment-table" commentId="809106" commentParentId="808839"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809106" href="?#comment-809106" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808839" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809106" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809106"> <div class="moveup"> <div class="ttypography"><p>Simply running two loops and checking every case would give a TLE. So, we might want to minimize the number of operations. For this, we would only consider the cases where the sum of indices is a multiple of an element.</p><p>For this, we would first create two loops, one within the other, first loop iterating i from 0 to (n — 1) with an incrementation of 1. By observation, we can see that the first index for which the sum of indices will be a multiple of arr[i] is (arr[i] — 2 — i).</p><p>So, in the nested loop we will run j = (arr[i] — 2 — i) till (n — 1) with an incrementation of arr[i]. We would ignore the cases where j &lt; 0 or j &gt;= n.</p><p>Finally, we need to check for how many cases this holds (arr[i] * arr[j] = i + j + 2 and j &gt; i).</p><p>Suggestions are welcomed!</p></div> </div> </div> <div class="reply info"> <a class="comment-809106 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809106 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809106"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808842" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808842" href="?#comment-808842" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808842" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-64" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-64</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808842"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){</p><p>ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);</p><p>int t;</p><p>cin &gt;&gt; t;</p><p>while(t--){</p><p>int n;</p> <pre>cin &gt;&gt; n;</pre><p>long long arr[n];</p> <pre>for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0;</pre><p>for(int i = 0; i &lt; n — 1; i++){</p> <pre>for(int j = arr[i] &amp;mdash; 2 &amp;mdash; i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } }</pre><p>}</p><p>cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;;</p><p>}</p> <pre>return 0;</pre><p>}</p><p>/* Accepted code</p><p>A different approach using arrays (as I don't know what vectors are, haven't read that)</p><p>I hope this is a optimal approach.</p><p>Any suggestions related to this are whole-heartedly welcomed.</p><p>Also, please guide me how could I have optimized the code to a much extent.</p><p>Thanks in advance!</p><p>Keep programming! </p><p>*/</p></div> </div> </div> <div class="reply info"> <a class="comment-808842 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808842 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808842"> <li> <div class="comment"> <table class="comment-table" commentId="808851" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808851" href="?#comment-808851" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808851" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808851"> <div class="moveup"> <div class="ttypography"><p>Use spoilers for writing codes, please!</p></div> </div> </div> <div class="reply info"> <a class="comment-808851 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808851 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808851"> <li> <div class="comment"> <table class="comment-table" commentId="808870" commentParentId="808851"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808870" href="?#comment-808870" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808851" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808870" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808870"> <div class="moveup"> <div class="ttypography"><p>Actually, this is my first comment. Don't know much of this stuff as of now, but I'll surely take care of it the very next time.</p></div> </div> </div> <div class="reply info"> <a class="comment-808870 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808870 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808870"> <li> <div class="comment"> <table class="comment-table" commentId="809760" commentParentId="808870"> <tr> <td class="left"> <div style="position: absolute; left: 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/sus" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sus" title="Pupil sus" class="rated-user user-green">sus</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 05:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809760" href="?#comment-809760" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808870" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809760" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1749651" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809760"> <div class="moveup"> <div class="ttypography"><p>what problem is your code for</p></div> </div> </div> <div class="reply info"> <a class="comment-809760 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809760 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809760"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808884" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sevlll777" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sevlll777" title="Grandmaster sevlll777" class="rated-user user-red">sevlll777</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808884" href="?#comment-808884" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808884" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="839333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808884"> <div class="moveup"> <div class="ttypography"><p>NICE CODESTYLE!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-808884 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808884 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808884"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809084" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cj2021" style="position: relative;"> <img src='https://userpic.codeforces.org/1927237/avatar/b64ff59bd9dcf385.jpg'/> </a> <div><a href="/profile/cj2021" title="Newbie cj2021" class="rated-user user-gray">cj2021</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809084" href="?#comment-809084" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809084" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1927237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809084"> <div class="moveup"> <div class="ttypography"><p>What is &amp;mdash?</p><p>Just curious to know as haven't seen it before.</p></div> </div> </div> <div class="reply info"> <a class="comment-809084 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809084 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809084"> <li> <div class="comment"> <table class="comment-table" commentId="809097" commentParentId="809084"> <tr> <td class="left"> <div style="position: absolute; left: 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/klahsiv" style="position: relative;"> <img src='https://userpic.codeforces.org/1590145/avatar/1bf86ae3d48e55b.jpg'/> </a> <div><a href="/profile/klahsiv" title="Expert klahsiv" class="rated-user user-blue">klahsiv</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809097" href="?#comment-809097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809084" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590145" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809097"> <div class="moveup"> <div class="ttypography"><p>it is minus (-).</p></div> </div> </div> <div class="reply info"> <a class="comment-809097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808848" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/willy108" style="position: relative;"> <img src='https://userpic.codeforces.org/1439320/avatar/d7f79ed4e8b32e9a.jpg'/> </a> <div><a href="/profile/willy108" title="Master willy108" class="rated-user user-orange">willy108</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808848" href="?#comment-808848" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808848" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="1439320" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808848"> <div class="moveup"> <div class="ttypography"><p>Div2 B can also be done in O(NsqrtN). We know that for a given pair of indeces i+j &lt; 2n, so any pair that a[i] * a[j] &lt; 2n will have to have one of the two terms be &lt;= sqrt(n) (with some off by one errors of course). So the algorithm is to store an array of pairs [array value, index] and sort that array by the value. If the array value is &lt;= sqrt(2n) we can naively loop over the rest of the array in O(n) time and check (be careful about overcount), and if the value is &gt; sqrt(n), we can ignore it. This works since when a[i] * a[j] &lt; 2n one of a[i] or a[j] has to be &lt;= sqrt(2n) and as a result, every pair will be counted.</p></div> </div> </div> <div class="reply info"> <a class="comment-808848 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808848 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808848"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808860" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bcollet" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bcollet" title="Master bcollet" class="rated-user user-orange">bcollet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808860" href="?#comment-808860" style="font-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="808860" 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="808860" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="858059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808860"> <div class="moveup"> <div class="ttypography"><p>I don't understand in div1 C why it's prefix of b, in the case i=3 we have $$$a_1+a_2+a_3=f_1+f_1+b_1+f_1+b_1+b_2$$$ so $$$f_1=(ap_i-2b_1-b_2)$$$ I believe the general formula is something in the taste of $$$f_1=(ap_i-ibp_{i-1}+bpt_{i-1})/i$$$ where bpt_i=b_1+2b_2+...+ib_i, I think I miss something<br />Edit: corrected</p></div> </div> </div> <div class="reply info"> <a class="comment-808860 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808860 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808860"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808865" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ParsaS" style="position: relative;"> <img src='https://userpic.codeforces.org/1590150/avatar/dc2d8c002d2c5e1e.jpg'/> </a> <div><a href="/profile/ParsaS" title="Candidate Master ParsaS" class="rated-user user-violet">ParsaS</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808865" href="?#comment-808865" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808865" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590150" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808865"> <div class="moveup"> <div class="ttypography"><p>Nice problems. thanks for almost fast editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-808865 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808865 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808865"> <li> <div class="comment"> <table class="comment-table" commentId="808871" commentParentId="808865"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/E404_Not_Found" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/E404_Not_Found" title="Expert E404_Not_Found" class="rated-user user-blue">E404_Not_Found</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808871" href="?#comment-808871" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808865" style="font-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="808871" 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="808871" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1662858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808871"> <div class="moveup"> <div class="ttypography"><p>Yes thanks for fast editorial :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808871 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808871 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808871"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808890" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vikash_8090_b" style="position: relative;"> <img src='https://userpic.codeforces.org/1969032/avatar/a0f23c893ae54e74.jpg'/> </a> <div><a href="/profile/vikash_8090_b" title="Newbie vikash_8090_b" class="rated-user user-gray">vikash_8090_b</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808890" href="?#comment-808890" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808890" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="1969032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808890"> <div class="moveup"> <div class="ttypography"><p>is there anyone who can't even solve one question of today's contest ..</p></div> </div> </div> <div class="reply info"> <a class="comment-808890 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808890 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808890"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808892" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808892" href="?#comment-808892" style="font-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="808892" 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="808892" class="CommentVoteFrame" data-commentRating="-6" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808892"> <div class="moveup"> <div class="ttypography"><p>Deleted :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808892 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808892 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808892"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808918" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prituladima" style="position: relative;"> <img src='https://userpic.codeforces.org/116750/avatar/ca46d0256a294b26.jpg'/> </a> <div><a href="/profile/prituladima" title="Pupil prituladima" class="rated-user user-green">prituladima</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808918" href="?#comment-808918" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808918" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="116750" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808918"> <div class="moveup"> <div class="ttypography"><p>Please explain div2c/div1a problem a little bit more. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808918 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808918 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808918"> <li> <div class="comment"> <table class="comment-table" commentId="808921" commentParentId="808918"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808921" href="?#comment-808921" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808918" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808921" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808921"> <div class="moveup"> <div class="ttypography"><p>Try out this <a href="https://youtube.com/c/MagentaCobra">channel</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808921 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808921 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808921"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808950" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jakab922" style="position: relative;"> <img src='https://userpic.codeforces.org/53532/avatar/f9515e974f3ebcb1.jpg'/> </a> <div><a href="/profile/jakab922" title="Specialist jakab922" class="rated-user user-cyan">jakab922</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808950" href="?#comment-808950" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808950" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="53532" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808950"> <div class="moveup"> <div class="ttypography"><p>I don't really understand the need for a recursive function for the stack emptying probabilities in <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a>. I mean given that you have a stack of size <code>n</code> and and <code>m</code> you can basically have an array of size <code>n + m</code> filled with <code>0</code>s and <code>1</code>s where <code>0</code> at the <code>i</code>th place means that the <code>i</code>th element was taken from the first stack. Any such array which has <code>n</code> <code>0</code>s and <code>m</code> <code>1</code>s correspond to one process and it's easy to see that whoever takes the last spot in the array gets emptied later which gives an easy way to calculate the probabilities. Namely $$$\binom{n + m - 1}{n - 1} / \binom{n + m}{n}$$$ for the first and similar to the other. </p></div> </div> </div> <div class="reply info"> <a class="comment-808950 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808950 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808950"> <li> <div class="comment"> <table class="comment-table" commentId="808959" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cuom1999" style="position: relative;"> <img src='https://userpic.codeforces.org/253776/avatar/934152bc42a0b10c.jpg'/> </a> <div><a href="/profile/cuom1999" title="Grandmaster cuom1999" class="rated-user user-red">cuom1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808959" href="?#comment-808959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="253776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808959"> <div class="moveup"> <div class="ttypography"><p>If $$$m=2$$$ and $$$n=1$$$, your approach gives $$$\frac{1}{3}$$$. The correct answer should be $$$\frac{1}{4}$$$. </p><p>P/S: I'm also curious if there is any combinatoric approach for this,<a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808959"> <li> <div class="comment"> <table class="comment-table" commentId="809004" commentParentId="808959"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809004" href="?#comment-809004" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809004" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809004"> <div class="moveup"> <div class="ttypography"><p>I would guess that there’s no easy closed form. You can evaluate in $$$O(n)$$$ however by counting right up paths from $$$(a,0)$$$ to $$$(x,y)$$$ for all $$$a$$$ and multiplying by $$$2^{-steps}$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-809004 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809004 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809004"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809366" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/geekpradd" style="position: relative;"> <img src='https://userpic.codeforces.org/367430/avatar/427394aa7f5a63a0.jpg'/> </a> <div><a href="/profile/geekpradd" title="Candidate Master geekpradd" class="rated-user user-violet">geekpradd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809366" href="?#comment-809366" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809366" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="367430" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809366"> <div class="moveup"> <div class="ttypography"><p>The problem with this is that all the possibilities are not equilikely, consider $$$m=2, n=1$$$ and let $$$1$$$ denote entries from the stack of size $$$n$$$. Then the probability of obtaining $$$100$$$ is $$$1/2$$$, while obtaining $$$010$$$ and $$$001$$$ has a probability of $$$1/4$$$. Your approach assumes a uniform prior probability (in which case the answer is indeed $$$1/3$$$ whereas here it is $$$1/4$$$ which is the probability of getting $$$001$$$)</p></div> </div> </div> <div class="reply info"> <a class="comment-809366 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809366 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809366"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thunderboltz" style="position: relative;"> <img src='https://userpic.codeforces.org/1170396/avatar/4f017b259605bc5c.jpg'/> </a> <div><a href="/profile/thunderboltz" title="Newbie thunderboltz" class="rated-user user-gray">thunderboltz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808951" href="?#comment-808951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170396" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808951"> <div class="moveup"> <div class="ttypography"><p>Problem Div2C/Div1A, Plz somebody explain 3rd hint. I didn't get why this condition must be true </p><p><code>The sum of the values of edges with positive weight must be ≥ the maximum value in the array.</code></p></div> </div> </div> <div class="reply info"> <a class="comment-808951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808951"> <li> <div class="comment"> <table class="comment-table" commentId="808995" commentParentId="808951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808995" href="?#comment-808995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808995" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808995"> <div class="moveup"> <div class="ttypography"><p>I like to think about C this way: The cheapest node is the root, and the most expensive node, X, is the one with the highest value, D. Therefore no matter how we make our edges, we need at least 1 path from node to X with distance D. So let's build 1 single edge of positive weight from 1 to X with weight D.</p><p>Now from node X, all other nodes are &lt;= D. We can use negative edges to go there. Now the problem just becomes &quot;assign as many negative edges as possible&quot; to the rest of the nodes. </p></div> </div> </div> <div class="reply info"> <a class="comment-808995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808995"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808971" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808971" href="?#comment-808971" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808971" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808971"> <div class="moveup"> <div class="ttypography"><p>In problem <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a> I agree with everything up to:</p> <blockquote><p>Once l is reached, we now note that the probability that the process &quot;gets closer&quot; to b is always equal to the probability of getting closer to a.</p> </blockquote><p>I agree with this quote if it was about each individual set of marked nodes and single step for them. Because for any individual set of marked nodes, those probabilities is just one over the number of options at the moment. But I don't understand why I should forget about everything else what happens with other parts of tree, because after single step which is neither towards <strong>a</strong> neither towards <strong>b</strong>, the number of options (nodes we can mark on next step) may change.</p></div> </div> </div> <div class="reply info"> <a class="comment-808971 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808971 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808971"> <li> <div class="comment"> <table class="comment-table" commentId="809006" commentParentId="808971"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809006" href="?#comment-809006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808971" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809006" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809006"> <div class="moveup"> <div class="ttypography"><p>That is correct, but to see how it stays the same you can think of it inductively. Use strong induction and assume probability is the same no matter what the state of the tree is. Then from $$$(x,y)$$$ you always have an equal probability of ending up in one of the two states you can transition to because $$$p$$$ is always the same. Every scenario you enter one state, there’s another scenario with the same probability that enters the other state. So, the probability of entering one of the two states is the same as the other, thus $$$0.5$$$. Hopefully that makes things more clear.</p></div> </div> </div> <div class="reply info"> <a class="comment-809006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809006"> <li> <div class="comment"> <table class="comment-table" commentId="809113" commentParentId="809006"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809113" href="?#comment-809113" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809006" style="font-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="809113" 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="809113" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809113"> <div class="moveup"> <div class="ttypography"><p>Oh thanks, it's clear now. So, base of induction is when only <strong>l</strong> reached, and we can show that probability to make step towards <strong>a</strong> and <strong>b</strong> is same because for each individual set you can go from <strong>l</strong> to <strong>b</strong> instead of going from <strong>l</strong> into <strong>a</strong>, using exactly same steps in between (those steps which doesn't change distances to <strong>a</strong> and <strong>b</strong>). And similar holds for next steps.</p></div> </div> </div> <div class="reply info"> <a class="comment-809113 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809113 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809113"> <li> <div class="comment"> <table class="comment-table" commentId="821713" commentParentId="809113"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 08:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821713" href="?#comment-821713" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809113" style="font-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="821713" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="821713" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-821713"> <div class="moveup"> <div class="ttypography"><p>Can you explain this?</p><p>Assume $$$X$$$ is initially node we chose. Then define a function $$$g$$$ :</p><p>$$$g[a][b][STATE]$$$ = probability to reach a before b while state of the tree we reach is $$$STATE$$$, and $$$a$$$, $$$b$$$ is length of path.</p><p><img alt=" " src="/predownloaded/c2/32/c232d053fe3fbd1dedc06e56db58a7c139157987.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>follow the image, I can see : $$$g[a][b][STATE_x] = \frac{1}{4} (g[a][b][STATE_d] + g[a][b][STATE_e] + g[a — 1][b][closer_a] + g[a][b — 1][closer_b])$$$</p><p>It can easy see that the probability can change. Or I wrong in some where?</p></div> </div> </div> <div class="reply info"> <a class="comment-821713 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821713 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821713"> <li> <div class="comment"> <table class="comment-table" commentId="821861" commentParentId="821713"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 18:25">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821861" href="?#comment-821861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821713" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="821861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-821861"> <div class="moveup"> <div class="ttypography"><p>I'll hide my long explanation under spoiler</p> <div class="spoiler"><b class="spoiler-title">horrible wall of text</b><div class="spoiler-content" style="display: none;"><p>To put things into words, I want to define some things. First, suppose we marked some $$$s_1, s_2, s_3 ... s_k$$$ vertices in exact this order. Then, let $$$P(s)$$$ to be probability to mark them in this sequence. It can be decomposed into $$$P(s) = p_1 \cdot p_2 \cdot p_3 \cdot ... \cdot p_k$$$ where $$$p_i = 1/o_{i-1}$$$ where $$$o_i$$$ is number of options at step $$$i$$$ — number of opened vertices, except $$$p_0 = 1/n$$$, or $$$o_0 = n$$$.</p><p>Then, let $$$l = LCA(a, b)$$$ where $$$LCA$$$ is lowest common ancestor. Then, let $$$x_v$$$ to be some sort of 'cost'. For each $$$v$$$ on path between $$$a$$$ and $$$l$$$ it will be distance to $$$l$$$, and $$$-1$$$ everywhere else. Similarly, for each $$$v$$$ on path between $$$b$$$ and $$$l$$$ let $$$y_v$$$ to be distance to $$$l$$$ and $$$-1$$$ everywhere else. Let</p> <center>$$$ A(s) = \max\limits_{v\in s}x_v \\ B(s) = \max\limits_{v\in s}y_v $$$</center><p>Then $$$A(s)$$$ is equal to how far we reach $$$a$$$, and $$$B(s)$$$ is equal to how far we reach $$$b$$$. Let say we are in situation $$$(A(s), B(s))$$$ after marking $$$s$$$, and therefore situation is pair of numbers. Situation $$$(-1,-1)$$$ corresponds that no vertex is marked on path from $$$a$$$ to $$$b$$$. Situation $$$(0,0)$$$ corresponds to only $$$l$$$ marked on path from $$$a$$$ to $$$b$$$. And situation $$$(1,0)$$$ corresponds to $$$l$$$ and single vertex towards $$$a$$$ is marked.</p><p>Finally, let say sequence of marks $$$s$$$ reached state $$$(A(s), B(s))$$$ if either $$$A(s) = x_{s_k}$$$ or $$$B(s) = y_{s_k}$$$, in other words, last vertex is on path from $$$a$$$ to $$$b$$$ and it did change situation.</p><p>Now, what we want to prove is following:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha+1,\beta)} P(s) = \sum\limits_{s\;reached\;(\alpha,\beta+1)} P(s)$$$</center><p><strong>For some fixed</strong> $$$s_1$$$, which is root we chosen. And the way we prove it is that $$$s$$$ that is reached $$$(\alpha+1,\beta)$$$ consists of $$$u$$$ that reached $$$(\alpha,\beta)$$$ plus additional steps: $$$w$$$ plus $$$s_k$$$. So $$$s = u..w..s_k$$$ where $$$..$$$ is concatenation. It's easy to see what none of vertices from $$$w$$$ is on path from $$$a$$$ to $$$b$$$. Also, it's easy to see that we could instead of choosing $$$s_k$$$ could choose vertex $$$z$$$ towards $$$b$$$, and it would have same probability. In other words $$$P(s) = P(u..w..z)$$$. And this $$$u..w..z$$$ should reach state $$$(\alpha, \beta+1)$$$. So it should be in right side sum of our equation we want to prove.</p><p>So, for any $$$s$$$ from left sum, we can make $$$s'$$$ from right sum in unique way, and it will have same $$$P(s) = P(s')$$$. Similarly, for any $$$s$$$ from right sum, we can make $$$s'$$$ from left sum in unique way, and it will have same $$$P(s) = P(s')$$$. So this is bijection, and each element from left sum corresponds to element from right sum with same value, so those sums should have same value. Therefore it's equality.</p><p>Initially I wanted to trim $$$s$$$ from $$$(\alpha+1,\beta)$$$ to $$$(\alpha,\beta)$$$ and show similar thing based on following sum:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha,\beta)} P(s)$$$</center><p>Which is probability to reach state $$$(\alpha, \beta)$$$, but luckily it didn't required. I'll use notation $$$P(reach(\alpha, \beta))$$$ for this probability.</p><p>Thing that is not covered though: why this equality can be translated into probability $$$= 1/2$$$? Well, from $$$(\alpha, \beta)$$$ you eventually will reach either $$$(\alpha+1,\beta)$$$ or $$$(\alpha,\beta+1)$$$, so you can see this as example of Law of total probability. $$$P(reach(\alpha, \beta)) = P(reach (\alpha+1, \beta)) + P(reach (\alpha, \beta+1))$$$, because events $$$(\alpha+1,\beta)$$$ and $$$(\alpha,\beta+1)$$$ are disjoint events given $$$(\alpha, \beta)$$$ is reached. And we proved they have equal probability so $$$P(reach(\alpha, \beta)) = 2\cdot P(reach (\alpha+1, \beta))$$$, so $$$P(reach (\alpha+1, \beta)) = 1/2\cdot P(reach(\alpha, \beta))$$$ which we actually use.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-821861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821861"> <li> <div class="comment"> <table class="comment-table" commentId="822027" commentParentId="821861"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/28/2021 13:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822027" href="?#comment-822027" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821861" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="822027" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822027"> <div class="moveup"> <div class="ttypography"><p>Oh, sorry, there is one missing part. We proved $$$P(reached(\alpha+1,\beta))=P(reached(\alpha,\beta+1))$$$ <strong>given</strong> $$$(\alpha,\beta)$$$ is reached, but this is actually what we need. This <strong>given</strong> condition is what I missed. Without <strong>given</strong> we could reach $$$(\alpha+1,\beta)$$$ from reaching $$$(\alpha+1,\beta-1)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-822027 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822027 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822027"> <li> <div class="comment"> <table class="comment-table" commentId="822370" commentParentId="822027"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 13:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822370" href="?#comment-822370" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822027" style="font-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="822370" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="822370" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822370"> <div class="moveup"> <div class="ttypography"><p>Thanks for amz explain. I realize that I had some missunderstand in the way we calc $$$P(reach\ A\ before\ B)$$$</p><p>This's exactly what in my mind one day ago: let $$$s = ...a...b...$$$ where $$$a$$$ and $$$b$$$ is node $$$a$$$ and node $$$b$$$, &quot;$$$...$$$&quot; mean some node between them which we chose them in exactly that order, or in other word, $$$s$$$ is state represent what we chose (exact in this order) I think $$$P(reach\ A\ before\ B)$$$ (or $$$P(A&lt;B)$$$) must be calculate in this way :</p><p>$$$P(A&lt;B) = \sum_{\substack{all\ s\ which\ a&lt;b}} P(s)$$$</p><p>But unfortunately, it's wrong (may be, or I still missunderstanding)</p><p>$$$P(A) = \sum_{\substack{all\ B[i]\ \subseteq\ A}} P(B[i])$$$ if and only if all $$$B[i]$$$ are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-822370 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822370 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822370"> <li> <div class="comment"> <table class="comment-table" commentId="822755" commentParentId="822370"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 22:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822755" href="?#comment-822755" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822370" style="font-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="822755" 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="822755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822755"> <div class="moveup"> <div class="ttypography"><p>$$$P(A &lt; B)$$$ in your terms is exactly what we need (if a = A and b = B).</p><p>I don't understand last formula, everything else looks fine.</p><p>And to find $$$P(A &lt; B)$$$ we use fact above and calculate all possible ways to reach $$$a$$$ earlier than $$$b$$$ we use $$$(\alpha, \beta)$$$ states using my notation: you either get $$$\alpha$$$ equal to dist to $$$a$$$ when $$$\beta$$$ = 0, or $$$\beta$$$ = 1, or 2, or 3...</p> <center>$$$ P(A &lt; B) = \\ =\sum\limits_{i=0}^{dist(b,l)}P(reach(dist(a,l),i)\;given\; reached(dist(a,l)-1,i)) \\ = \sum\limits_{i=0}^{dist(b,l)}P(reached(dist(a,l)-1,i))\cdot \frac{1}{2} $$$</center><p>Or you can rephrase task into other task with two kind of balls. What probability to remove all balls of one kind earlier than other, if you pick one or other kind of ball with probability 1/2.</p></div> </div> </div> <div class="reply info"> <a class="comment-822755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822755"> </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="808983" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/xsc" style="position: relative;"> <img src='https://userpic.codeforces.org/343/avatar/9eaf243b1eb8c3d4.jpg'/> </a> <div><a href="/profile/xsc" title="Specialist xsc" class="rated-user user-cyan">xsc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808983" href="?#comment-808983" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808983" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="343" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808983"> <div class="moveup"> <div class="ttypography"><p>Div2 D, O(N^4) solution <a href="/contest/1541/submission/120623566" title="Посылка 120623566 от xsc">120623566</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808983 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808983 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808983"> <li> <div class="comment"> <table class="comment-table" commentId="809278" commentParentId="808983"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DavidXu_JJ" style="position: relative;"> <img src='https://userpic.codeforces.org/2003708/avatar/623dc8036b4e9d72.jpg'/> </a> <div><a href="/profile/DavidXu_JJ" title="Expert DavidXu_JJ" class="rated-user user-blue">DavidXu_JJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809278" href="?#comment-809278" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808983" style="font-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="809278" 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="809278" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2003708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809278"> <div class="moveup"> <div class="ttypography"><p>Your code really helps me a lot in debugging,thanks.</p><p>By the way,it's weired that I get Wrong6 when I try to optimize to O(N^3*logN) by binary search on tree.</p><p>I have tested my function on other online judge and my function seems to be correct.</p></div> </div> </div> <div class="reply info"> <a class="comment-809278 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809278 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809278"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809018" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ducati" style="position: relative;"> <img src='https://userpic.codeforces.org/699102/avatar/eff3c352646e914e.jpg'/> </a> <div><a href="/profile/ducati" title="Grandmaster ducati" class="rated-user user-red">ducati</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 03:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809018" href="?#comment-809018" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809018" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="699102" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809018"> <div class="moveup"> <div class="ttypography"><p>Although Div.2 D is harder than ever, in my opinion, it's such a useful and excellent problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-809018 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809018 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809018"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809046" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KanishkGoel" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/KanishkGoel" title="Expert KanishkGoel" class="rated-user user-blue">KanishkGoel</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809046" href="?#comment-809046" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809046" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1917239" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809046"> <div class="moveup"> <div class="ttypography"><p>Is it usual for people to post solutions online during the contest like this channel? <a href="https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ">https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809046 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809046 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809046"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809051" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809051" href="?#comment-809051" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809051"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain why this submission <a href="/contest/1541/submission/120562335" title="Посылка 120562335 от Karnania7201">120562335</a> is failing for Div2 B? It would be a great help.</p></div> </div> </div> <div class="reply info"> <a class="comment-809051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809051"> <li> <div class="comment"> <table class="comment-table" commentId="809076" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809076" href="?#comment-809076" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809076" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809076"> <div class="moveup"> <div class="ttypography"><p>Bro you did not included the condition that i and j should be different i.e (i != j) because it is given in question that no are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-809076 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809076 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809076"> <li> <div class="comment"> <table class="comment-table" commentId="809079" commentParentId="809076"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:08">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809079" href="?#comment-809079" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809076" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809079" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809079"> <div class="moveup"> <div class="ttypography"><p>I think its covered as I started j from i+1. I tried that explicitly too but it didn't work. I wrote the same idea in a different way and it worked but this kind of implementation is not working.</p></div> </div> </div> <div class="reply info"> <a class="comment-809079 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809079 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809079"> <li> <div class="comment"> <table class="comment-table" commentId="809082" commentParentId="809079"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809082" href="?#comment-809082" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809079" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809082" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809082"> <div class="moveup"> <div class="ttypography"><p>yeah, you are right, I run your code using vector instead of creating memeset it worked fine, i guess there is some problem in that. <a href="https://codeforces.com/contest/1541/submission/120633207">120633207</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809082 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809082 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809082"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809081" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_NICkk" style="position: relative;"> <img src='https://userpic.codeforces.org/1543175/avatar/6084dd87f2c1cad9.jpg'/> </a> <div><a href="/profile/_NICkk" title="Expert _NICkk" class="rated-user user-blue">_NICkk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809081" href="?#comment-809081" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809081" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1543175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809081"> <div class="moveup"> <div class="ttypography"><p>Only fault in your code is that you didn't used memset correctly </p><p>I just changed your memset with this &quot; memset(ind, 0, sizeof(ind)) &quot; and it worked perfectly fine</p></div> </div> </div> <div class="reply info"> <a class="comment-809081 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809081 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809081"> <li> <div class="comment"> <table class="comment-table" commentId="809091" commentParentId="809081"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:37">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809091" href="?#comment-809091" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809081" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809091" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809091"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot to both of you. I shouldn't have used it without properly knowing about it. </p></div> </div> </div> <div class="reply info"> <a class="comment-809091 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809091 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809091"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809064" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vrintle" style="position: relative;"> <img src='https://userpic.codeforces.org/1991777/avatar/24d9007095afbbb6.jpg'/> </a> <div><a href="/profile/vrintle" title="Master vrintle" class="rated-user user-orange">vrintle</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809064" href="?#comment-809064" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809064" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1991777" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809064"> <div class="moveup"> <div class="ttypography"><p>Instead of $$$a_i \cdot a_j \leq 2n$$$, we could also check $$$a_i \cdot a_j \leq i+n$$$ which is a bit faster ($$$ \sim 62ms$$$).</p></div> </div> </div> <div class="reply info"> <a class="comment-809064 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809064 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809064"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809066" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809066" href="?#comment-809066" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809066" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809066"> <div class="moveup"> <div class="ttypography"><p>can anyone explain B. pleasant pairs more easy words?? </p></div> </div> </div> <div class="reply info"> <a class="comment-809066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809066"> <li> <div class="comment"> <table class="comment-table" commentId="809067" commentParentId="809066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809067" href="?#comment-809067" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809067" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809067"> <div class="moveup"> <div class="ttypography"><p>And also what is ask in 3rd question i cant understand what asked in it</p></div> </div> </div> <div class="reply info"> <a class="comment-809067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809067"> <li> <div class="comment"> <table class="comment-table" commentId="809070" commentParentId="809067"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809070" href="?#comment-809070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809067" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809070"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">https://www.youtube.com/watch?v=xCj_ZR5kENo</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809098" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809098" href="?#comment-809098" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809098" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809098"> <div class="moveup"> <div class="ttypography"><p>For those who are searching for a simple solution for great Graphs problems in O (nlogn). <a href="https://codeforces.com/contest/1541/submission/120600816">https://codeforces.com/contest/1541/submission/120600816</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809098 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809098 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809098"> <li> <div class="comment"> <table class="comment-table" commentId="809119" commentParentId="809098"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fjvzr" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/fjvzr" title="Newbie fjvzr" class="rated-user user-gray">fjvzr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809119" href="?#comment-809119" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809098" style="font-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="809119" 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="809119" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1623986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809119"> <div class="moveup"> <div class="ttypography"><p>Bro can u explain this soln????? i thought of taking all pairs that give negative edges except for the adjacent pairs.... bt getting wrong ans in 3rd 4th test case.....</p><p>while(n&gt;2) { sum-=(n-2)*(llabs(a[j]-a[i])); n--; // n = size i++; // i = 0 j--; // j = n-1 } cout&lt;&lt;sum&lt;&lt;endl;</p><p><a href="https://codeforces.com/contest/1541/submission/120636509">mysoln</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809119 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809119 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809119"> <li> <div class="comment"> <table class="comment-table" commentId="809124" commentParentId="809119"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809124" href="?#comment-809124" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809119" style="font-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="809124" 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="809124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809124"> <div class="moveup"> <div class="ttypography"><p>My solution is simple. First sort the array. </p><p>Then start connecting adjacent values with their differences. This way sum of all edges with positive weight will be same as the sum of adjacent differences in the array.</p><p>After that start making negative edges for every i. So each i will have i negative edges. Where negative weight is same as -(arr[i] — arr[j]).</p><p>Instead of search it for every j I have formula as (prefixsum till i) — arr[i]*i</p></div> </div> </div> <div class="reply info"> <a class="comment-809124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809124"> <li> <div class="comment"> <table class="comment-table" commentId="809132" commentParentId="809124"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809132" href="?#comment-809132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809124" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809132"> <div class="moveup"> <div class="ttypography"><p>can you tell me why are we sorting the array for a particular node call it x we need to add a negative weight from x to 1 , x to 2 x to 3 till x to x-1 keeping in mind the the path sum doesn't become negative so why are we sorting the array</p></div> </div> </div> <div class="reply info"> <a class="comment-809132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809132"> <li> <div class="comment"> <table class="comment-table" commentId="809135" commentParentId="809132"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809135" href="?#comment-809135" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809135" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809135"> <div class="moveup"> <div class="ttypography"><p>We are sorting values only once so as to connect neighboring nodes with minimum values,i.e. difference b/w consecutive values.<br /> From this sum of positive edges will be minimum.</p></div> </div> </div> <div class="reply info"> <a class="comment-809135 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809135 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809135"> <li> <div class="comment"> <table class="comment-table" commentId="809139" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809139" href="?#comment-809139" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809139" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809139"> <div class="moveup"> <div class="ttypography"><p>ohhh thanks I got it</p></div> </div> </div> <div class="reply info"> <a class="comment-809139 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809139 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809139"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809145" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809145" href="?#comment-809145" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809145" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809145"> <div class="moveup"> <div class="ttypography"><p>My solution is working now I only needed to sort the array my code would have been accepted during the contest :(</p></div> </div> </div> <div class="reply info"> <a class="comment-809145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809145"> </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="809116" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ken_KaNeKi_997" style="position: relative;"> <img src='https://userpic.codeforces.org/1737228/avatar/50ceb845253df5d4.jpg'/> </a> <div><a href="/profile/Ken_KaNeKi_997" title="Newbie Ken_KaNeKi_997" class="rated-user user-gray">Ken_KaNeKi_997</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809116" href="?#comment-809116" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809116" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1737228" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809116"> <div class="moveup"> <div class="ttypography"><p>can anyone explain div2 B plz</p></div> </div> </div> <div class="reply info"> <a class="comment-809116 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809116 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809116"> <li> <div class="comment"> <table class="comment-table" commentId="809204" commentParentId="809116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809204" href="?#comment-809204" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809116" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809204" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809204"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/92199#comment-809178">here</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809204 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809204 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809204"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809122" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809122" href="?#comment-809122" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809122" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809122"> <div class="moveup"> <div class="ttypography"><p>Beautiful Problems. Amazing Round!!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-809122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809122"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809156" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dummybawa" style="position: relative;"> <img src='https://userpic.codeforces.org/1704408/avatar/1522f670cd21321.jpg'/> </a> <div><a href="/profile/dummybawa" title="Expert dummybawa" class="rated-user user-blue">dummybawa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809156" href="?#comment-809156" style="font-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="809156" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809156" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1704408" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809156"> <div class="moveup"> <div class="ttypography"><p>UPD: It's wrong. </p></div> </div> </div> <div class="reply info"> <a class="comment-809156 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809156 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809156"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809178" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809178" href="?#comment-809178" style="font-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="809178" 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="809178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809178"> <div class="moveup"> <div class="ttypography"><p>For DIV 2C/1A can anyone explain with this test case N = 6 and D = 0 1 2 3 2 3. What are the edges that we can have with their weights?</p></div> </div> </div> <div class="reply info"> <a class="comment-809178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809178"> <li> <div class="comment"> <table class="comment-table" commentId="809198" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Zemrith" style="position: relative;"> <img src='https://userpic.codeforces.org/1159882/avatar/2a6566e372882267.jpg'/> </a> <div><a href="/profile/Zemrith" title="Expert Zemrith" class="rated-user user-blue">Zemrith</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809198" href="?#comment-809198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-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="809198" 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="809198" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159882" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809198"> <div class="moveup"> <div class="ttypography"><p>Hello! The answer would be -18.</p><p>Diagram: <img alt=" " src="/predownloaded/8c/88/8c88a0230dea9f499896ee59def659611c605976.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Notice that once you sort the distances, the adjacent nodes have no effect on your final answer. But you can add negative edges as long as they are not adjacent, resulting in such a diagram. Hence you can use prefix sums to solve the problem. (if x nodes came before this, for each node, the answer to add is (x-1)*curr value — csum of first (x-1) nodes). </p><p>Hope that made sense!</p></div> </div> </div> <div class="reply info"> <a class="comment-809198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809198"> <li> <div class="comment"> <table class="comment-table" commentId="809218" commentParentId="809198"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:27">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809218" href="?#comment-809218" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809218" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809218"> <div class="moveup"> <div class="ttypography"><p>Thank you <a class="rated-user user-cyan" href="/profile/Zemrith" title="Специалист Zemrith">Zemrith</a> for so much detail explanation and the solution too it helped me a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-809218 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809218 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809218"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809199" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809199" href="?#comment-809199" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809199" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809199"> <div class="moveup"> <div class="ttypography"><p>first sort the array they will from non negative weight edges. 0 -&gt; 1 -&gt; 2 -&gt; 2 -&gt; 3 -&gt; 3 so the non negative weights will be 1 | 1 | 0 | 1 | 0. form here greedily build most negative weights(backward edges) such that there are no negative cycles.</p></div> </div> </div> <div class="reply info"> <a class="comment-809199 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809199 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809199"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809203" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809203" href="?#comment-809203" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809203" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809203"> <div class="moveup"> <div class="ttypography"><p>First you can sort D and get: <code> N = 6, D = [0, 1, 2, 2, 3, 3] </code></p><p>Now calculate the diffs:</p><p><code>diffs = [1, 1, 0, 1, 0]</code></p><p>The edges for this graph could be something like this:</p> <pre><code> 1 1 0 1 0 &lt;- forward edges 1 &lt;-&gt; 2 &lt;-&gt; 3 &lt;-&gt; 4 &lt;-&gt; 5 &lt;-&gt; 6 -1 -1 0 -1 0 &lt;- backward edges </code></pre><p>Now you have to add more negatives edges, and you could do this by choosing some <code>i</code> and <code>j</code>, <code>i &lt; j</code> and add an edges from <code>j</code> to <code>i</code>, and the weight will be sum of the values from <code>diff[i]</code> to <code>diff[j]</code>.</p><p>Another way to think about this is: look at <code>D</code> array, it represents distances between adjacent nodes, all we have to do is add all of the edges with length 2, then all of the edges of length 3, ..., all of the edges of length <code>N - 1</code>.</p><p>So, for our case we would have these edges</p> <pre><code>a b W ------- 1 2 - 1 2 3 - 1 3 4 - 0 &lt;- adjacent forward edges 4 5 - 1 5 6 - 0 2 1 - -1 3 2 - -1 4 3 - 0 &lt;- adjacent backward edges 5 4 - -1 6 5 - 0 3 1 - -2 4 2 - -1 5 3 - -1 &lt;- edges of length 2 6 4 - -1 4 1 - -2 5 2 - -2 &lt;- edges of length 3 6 3 - -1 5 1 - -3 6 2 - -2 &lt;- edges of length 4 6 1 - -3 &lt;- edges of length 5 </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809203 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809203 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809203"> <li> <div class="comment"> <table class="comment-table" commentId="809221" commentParentId="809203"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809221" href="?#comment-809221" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809203" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809221" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809221"> <div class="moveup"> <div class="ttypography"><p>Thank You <a class="rated-user user-green" href="/profile/ilidar" title="Ученик ilidar">ilidar</a> for clearing my doubt and for detailed explaination.</p></div> </div> </div> <div class="reply info"> <a class="comment-809221 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809221 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809221"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809280" href="?#comment-809280" style="font-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="809280" revisionCount="7" revision="7"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">7</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809280" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+18</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809280"> <div class="moveup"> <div class="ttypography"><p>Could someone please provide a more strict intuition or insight of Div2D/Div1B of why &quot;the actual probability p does not matter&quot;? The intuition in the editorial is still alien to me of why those choices of not progess toward to either stacks (and probability 'p' also changes from time to time too) doesn't matter.</p><p>Update: Here is the intuition I came up with (The strict proof can be found in the comment of the author below)</p><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left) in some states of the current tree.</p><p>now, we will try break this $$$dp_{i,j}$$$ down into the sum of $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$</p><p>We will try to illustrate this with trying to split and color, either red or blue, a stick of length $$$1$$$. The length of the sticks representing the 'probability', and the color of the sticks will represent $$$dp_{i-1,j}$$$(red) or $$$dp_{i,j-1}$$$(blue), depending on the color.</p><p>Suppose in the current state, we have probability $$$p$$$ for choosing to pop each stacks, and the rest $$$1-2p$$$ of doing nothing. The picture will look like this:</p><p><a href="https://ibb.co/q9HjQTm"><img alt="Tree-Array-Rep" border="0" src="/predownloaded/13/57/135732d2b0967af0f76c1dba28df72086f234c7d.png" style="max-width: 100.0%;max-height: 100.0%;" /></a></p><p>We will split the stick equally(*) into several sticks of length $$$p$$$, and then color two of them red and blue. (* We can split it evenly because in the original problem, $$$p$$$ is in the form $$$\frac{1}{number\ of\ candidate\ unmark\ nodes}$$$ ) Now, the remaining sticks represent the state of $$$dp_{i,j}$$$ again (in some other state of the entire tree, so might be in some different $$$p$$$). That means we will split those sticks similary.</p><p>The key observations is:</p><p>1) We know that, in the original problem, if we keep picking nodes that aren't progressing toward the target nodes, we will run out of nodes eventually and finally choose the two nodes. That means, all the sticks will eventually colored into 'red' and 'blue'.</p><p>2) When we split a stick into several smaller equal length sticks, we will color two of them into red and blue. <strong>Those two sticks always have the same length</strong>. That means, the total length of blue sticks and the total length of red sticks will be equal in the end.</p><p>Analogically, that means, eventually, $$$dp_{i,j}$$$ will split into $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$ evenly, no matter $$$p$$$ might be or the state of tree of $$$dp_{i,j}$$$ might be. Therefore, $$$dp_{i,j} = \frac{1}{2} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-809280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809280"> <li> <div class="comment"> <table class="comment-table" commentId="809284" commentParentId="809280"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809284" href="?#comment-809284" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809280" style="font-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="809284" 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="809284" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809284"> <div class="moveup"> <div class="ttypography"><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left), with having arbitary probability $$$0 &lt; p \leq 0.5$$$ of chosing to pick the top of each stack (and $$$1-2p$$$ for doing nothing). Then</p><p>$$$dp_{i,j}=\int_{0}^{0.5} x \cdot (dp_{i-1,j}+dp_{i,j-1}) + (1-2x) \cdot dp_{i,j} \,dx$$$</p><p>Solving the equation, we get $$$dp_{i,j}=\frac{1}{6} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$ What is the mistake in this logic?</p></div> </div> </div> <div class="reply info"> <a class="comment-809284 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809284 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809284"> <li> <div class="comment"> <table class="comment-table" commentId="809399" commentParentId="809284"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809399" href="?#comment-809399" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809284" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809399" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809399"> <div class="moveup"> <div class="ttypography"><p>The biggest issue with this logic is that it's assuming $$$p$$$ is arbitrary chosen from a certain state. While $$$p$$$ can be anything in the world, it is always an exact number from a certain state, hence why an integral is wrong. </p><p>As a different type of intuition, you can think, &quot;is it more likely to reach $$$(i-1, j)$$$ than state $$$(i, j-1)$$$&quot;? and vice versa. For me at least, I don't see how it's possible for either of those questions to be true, so they should be equal.</p><p>If you're looking for a more rigorously correct $$$dp$$$, it would look something like this.</p> <div class="spoiler"><b class="spoiler-title">Proof</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp_{i, j, S}$$$ denote the probability of reaching some node $$$i$$$ distance away before some node $$$j$$$ distance away where $$$S$$$ is a representation of the entire state of of the process (not necessarily an integer). I think you already understood why we can assume the $$$lca$$$ is already reached. We aim to show that $$$S$$$ does not matter in our calculation. Assume inductively that $$$S$$$ does not matter. So, we can assume that states $$$(i-1, j)$$$ and states $$$(i, j-1)$$$ are irrelevant to $$$S$$$. Hence, the part we need to care about is $$$(1-2p) dp_{i, j, S \rightarrow S_a}$$$. A way of thinking about this part of the transition is moving through the collection of $$$S$$$ with the state $$$(i, j)$$$. Obviously, the $$$dp$$$ is a $$$DAG$$$ because no state $$$S$$$ can reach another. Each bounce takes a certain probability $$$p$$$ which is just multiplied in the current path. So, for each state $$$S$$$ with state $$$(i, j)$$$, we have a certain probability to reach it by simply calculating $$$dp$$$ along a DAG as is traditional. Then, from those states of $$$(i, j)$$$ you transition to $$$(i, j-1)$$$ with an equal probability $$$(i-1, j)$$$. So, they have to be equal. Finally, this argument holds for any initial state $$$S$$$ that you reach, so we can conclude that, from any state $$$S$$$ with a state of $$$(i, j)$$$, the probability of transitions to $$$(i-1, j)$$$ and $$$(i, j-1)$$$ are always exactly $$$0.5$$$.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-809399 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809399 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809399"> <li> <div class="comment"> <table class="comment-table" commentId="809701" commentParentId="809399"> <tr> <td class="left"> <div style="position: absolute; left: 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/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809701" href="?#comment-809701" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809399" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809701" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809701"> <div class="moveup"> <div class="ttypography"><p>I see, thank you so much!</p></div> </div> </div> <div class="reply info"> <a class="comment-809701 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809701 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809701"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809298" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/satyam_singh93" style="position: relative;"> <img src='https://userpic.codeforces.org/1763011/avatar/9d9fa405de19ab0e.jpg'/> </a> <div><a href="/profile/satyam_singh93" title="Newbie satyam_singh93" class="rated-user user-gray">satyam_singh93</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809298" href="?#comment-809298" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809298" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1763011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809298"> <div class="moveup"> <div class="ttypography"><p>I am getting wrong ans . could someone tell me where the code make differene ( [yestrday competiton problem .</p><p>`](<a href="https://codeforces.com/contest/1541/problem/B)">https://codeforces.com/contest/1541/problem/B)</a>.</p> <pre><code>int main( ) { clock_t begin = clock(); file_i_o(); // Write your code here.... int t; cin&gt;&gt;t; while(t-- ){ int n; cin&gt;&gt;n; vector&lt;pair&lt;int,int&gt;&gt;v; v.push_back({0,0}); loop(i,0,n) { int x; cin&gt;&gt;x; v.pb({x,i+1}); } sort(v.begin()+1,v.end()); int count =0; for(int i=1 ; i&lt;=n;i++) { for(ll j=i+1;j&lt;=n;j++) { ll left = v[i].first * v[j].first; ll right = v[i].second + v[j].second; if(left == right) count++; if(left &gt; 2*n ) break; } } cout&lt;&lt;count&lt;&lt;endl; } </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809298 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809298 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809298"> <li> <div class="comment"> <table class="comment-table" commentId="809305" commentParentId="809298"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809305" href="?#comment-809305" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809298" style="font-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="809305" 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="809305" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809305"> <div class="moveup"> <div class="ttypography"><p>v[i].first * v[j].first can create overflow. So, you need to convert them to long long by using</p><p>ll left = 1LL * v[i].first * v[j].first;</p><p>instead and it would pass.</p><p>(Simply save the value in long long won't help. You need to convert them to long long before doing multiplication. 1LL* is one way)</p></div> </div> </div> <div class="reply info"> <a class="comment-809305 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809305 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809305"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809309" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809309" href="?#comment-809309" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809309" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809309"> <div class="moveup"> <div class="ttypography"><p>Hi, in problem Div1.B/Div2.D; I can't wrap my head around $$$F[x][y]=F[x−1][y]/2+F[x][y−1]/2$$$. Why is it not $$$F[x][y]=F[x−1][y+1]/2+F[x+1][y−1]/2$$$, can someone please explain to me why is my transition wrong and/or why is the aforementioned transition correct? </p></div> </div> </div> <div class="reply info"> <a class="comment-809309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809309"> <li> <div class="comment"> <table class="comment-table" commentId="809311" commentParentId="809309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809311" href="?#comment-809311" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809311" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809311"> <div class="moveup"> <div class="ttypography"><p>x and y is the distance left for each side right? So, if you take one out, it won't make sense to add that one to the other side since the distance should be either x-1 and y or x and y-1.</p></div> </div> </div> <div class="reply info"> <a class="comment-809311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809311"> <li> <div class="comment"> <table class="comment-table" commentId="809339" commentParentId="809311"> <tr> <td class="left"> <div style="position: absolute; left: 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/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809339" href="?#comment-809339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809339" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809339"> <div class="moveup"> <div class="ttypography"><p>Thank you so much I understand. I had a minor misunderstanding of the parameters to the dp state.</p></div> </div> </div> <div class="reply info"> <a class="comment-809339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809339"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809371" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:13">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809371" href="?#comment-809371" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809371" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809371"> <div class="moveup"> <div class="ttypography"><p>PLease explain why 2 same codes are not giving the same ans</p><p>code forces round 728 div2<br />Problem B :<a href="https://codeforces.com/contest/1541/problem/B">https://codeforces.com/contest/1541/problem/B</a></p><p>AC Submission : <a href="https://ide.codingblocks.com/s/579769">https://ide.codingblocks.com/s/579769</a></p><p>Wrong output Submission :<a href="https://ide.codingblocks.com/s/579771">https://ide.codingblocks.com/s/579771</a></p><p>Difference is using of macro (node) instead of pair&lt;int,int&gt; </p><p>Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-809371 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809371 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809371"> <li> <div class="comment"> <table class="comment-table" commentId="809379" commentParentId="809371"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809379" href="?#comment-809379" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809371" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809379" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809379"> <div class="moveup"> <div class="ttypography"><p>If i am using #define node pair&lt;int,int&gt; it is getting accepted but when i am using typedef pair&lt;int,int&gt; node; it is giving wrong answer</p><p>Why this is happening ?? Is it a bug??</p></div> </div> </div> <div class="reply info"> <a class="comment-809379 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809379 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809379"> <li> <div class="comment"> <table class="comment-table" commentId="809407" commentParentId="809379"> <tr> <td class="left"> <div style="position: absolute; left: 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/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 19:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809407" href="?#comment-809407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809379" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809407" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809407"> <div class="moveup"> <div class="ttypography"><p>Not really sure why this is happening.</p><p>However, I think the problem is the position of #define int long long. So, for #define pair&lt;int,int&gt; node it seems that compiler change node -&gt; pair&lt;int,int&gt; -&gt; pair&lt;long long, long long&gt;. However, when you do typedef, it still keeps in pair&lt;int, int&gt; which creates an overflow problem later on. </p><p>I did try moving #define int long long up above typedef and the code pass. So, my best guess is #define int long long only replace int after that position with long long. Thus, node is still pair&lt;int, int&gt; in the typedef solution, while node is changed to pair&lt;long long, long long&gt; in the second solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-809407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809407"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809627" href="?#comment-809627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809627"> <div class="moveup"> <div class="ttypography"><p>May I ask why in the Div1D solution ci=i-bi, I think it should be ci=bi ...</p></div> </div> </div> <div class="reply info"> <a class="comment-809627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809627"> <li> <div class="comment"> <table class="comment-table" commentId="809631" commentParentId="809627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809631" href="?#comment-809631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809631" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809631"> <div class="moveup"> <div class="ttypography"><p>Check the definition of bi again dude. bi here means <strong>number of elements greater than pi</strong>. So to get ci, which is <strong>number of elements smaller than pi</strong>, you need i-bi.</p></div> </div> </div> <div class="reply info"> <a class="comment-809631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809631"> <li> <div class="comment"> <table class="comment-table" commentId="809636" commentParentId="809631"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809636" href="?#comment-809636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809636"> <div class="moveup"> <div class="ttypography"><p>I read it again. If I read it correctly, bi stands for j&lt;i,pj&gt;pi, and ci stands for j&gt;i,pj&lt;pi. For example, p={1,3,5,4,6,2}, I think b4=1,c4=1, please point out my problem</p></div> </div> </div> <div class="reply info"> <a class="comment-809636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809636"> <li> <div class="comment"> <table class="comment-table" commentId="809638" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809638" href="?#comment-809638" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809638" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809638"> <div class="moveup"> <div class="ttypography"><p>oh, the array index starts from 1</p></div> </div> </div> <div class="reply info"> <a class="comment-809638 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809638 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809638"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809639" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809639" href="?#comment-809639" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809639" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809639"> <div class="moveup"> <div class="ttypography"><p>You are right.</p><p>I guess it might just be typo and ci stands for j&lt;i, pj&lt;pi. At least with this definition of ci the algorithm seems correct :)</p></div> </div> </div> <div class="reply info"> <a class="comment-809639 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809639 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809639"> <li> <div class="comment"> <table class="comment-table" commentId="809641" commentParentId="809639"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809641" href="?#comment-809641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809639" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809641"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-809641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809641"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809705" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/darthrevenge" style="position: relative;"> <img src='https://userpic.codeforces.org/1567000/avatar/ee31d2a91a9575b9.jpg'/> </a> <div><a href="/profile/darthrevenge" title="Candidate Master darthrevenge" class="rated-user user-violet">darthrevenge</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809705" href="?#comment-809705" style="font-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="809705" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809705" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1567000" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809705"> <div class="moveup"> <div class="ttypography"><p>Here's my solution of B div 1 / D div 2 without LCA, using single DFS per node. <a href="/contest/1540/submission/120700765" title="Посылка 120700765 от darthrevenge">120700765</a> It is similar to what <a class="rated-user user-violet" href="/profile/OleschY" title="Кандидат в мастера OleschY">OleschY</a> suggested above. I've tried to describe it in the <a href="https://codeforces.com/blog/entry/92284">blog</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-809705 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809705 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809705"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809951" href="?#comment-809951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809951"> <div class="moveup"> <div class="ttypography"><p>Can someone explain how you can find the LCA for each pair so quick? Iterating through every root is and then considering every pair is already N^3</p></div> </div> </div> <div class="reply info"> <a class="comment-809951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809951"> <li> <div class="comment"> <table class="comment-table" commentId="809965" commentParentId="809951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PurpleCrayon" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809965" href="?#comment-809965" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809965" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="1604355" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809965"> <div class="moveup"> <div class="ttypography"><p>There are a couple ways you could do it:</p> <ol> <li>Just use standard binary lifting (initialize once for each root). This runs in $$$\mathcal{O}(n^3 \log{}n)$$$, and should pass under the given constraints. You could also just use $$$\mathcal{O}(1)$$$ lca using an rmq over an euler tour.</li> <li>You could use a version of dp, where $$$dp[a][b] = lca(a, b)$$$. If the depth of $$$a$$$ is greater than the depth of $$$b$$$, $$$dp[a][b] = dp[parent[a]][b]$$$, otherwise $$$dp[a][b] = dp[a][parent[b]]$$$. The base cases are $$$dp[a][a] = a$$$ for all $$$a$$$. This runs in $$$\mathcal{O}(n^3)$$$.</li> <li>You could extend this idea and do the main solution's dp directly on the tree (without ever worrying about lca's). The recurrence is equivalent to the main solution ($$$dp[a][b] = \frac{dp[parent[a]][b]+dp[a][parent[b]]}{2}$$$ with the base cases being one node is an ancestor of the other.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-809965 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809965 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809965"> <li> <div class="comment"> <table class="comment-table" commentId="809967" commentParentId="809965"> <tr> <td class="left"> <div style="position: absolute; left: 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/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809967" href="?#comment-809967" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809965" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809967" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809967"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the detailed answer!</p></div> </div> </div> <div class="reply info"> <a class="comment-809967 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809967 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809967"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="810320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Anurag_20" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Anurag_20" title="Specialist Anurag_20" class="rated-user user-cyan">Anurag_20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/30/2021 19:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810320" href="?#comment-810320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810320" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1600346" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810320"> <div class="moveup"> <div class="ttypography"><p>O(n2) is also working for div2 C Great Graphs. <a href="https://codeforces.com/contest/1540/submission/120964787">https://codeforces.com/contest/1540/submission/120964787</a></p></div> </div> </div> <div class="reply info"> <a class="comment-810320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810320"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="813828" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/T404" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/T404" title="Master T404" class="rated-user user-orange">T404</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/09/2021 19:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-813828" href="?#comment-813828" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="813828" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="523287" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-813828"> <div class="moveup"> <div class="ttypography"><p>Div1D can be done in $$$O(n \sqrt{n})$$$. We can use square root decomposition to replace all BITs in tutorial. Since a value in a non-updated position changes by at most one and all values change in the same direction, the full recomputation is only needed in the updated position and we can perform an incremental change in $$$O(1)$$$ for values in each non-updated positions.</p><p><a href="https://codeforces.com/contest/1540/submission/121831547">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-813828 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-813828 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-813828"> <li> <div class="comment"> <table class="comment-table" commentId="834051" commentParentId="813828"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KeyID" style="position: relative;"> <img src='https://userpic.codeforces.org/226684/avatar/10e3671716bf6859.jpg'/> </a> <div><a href="/profile/KeyID" title="Grandmaster KeyID" class="rated-user user-red">KeyID</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/29/2021 12:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-834051" href="?#comment-834051" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-813828" style="font-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="834051" 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="834051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="226684" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-834051"> <div class="moveup"> <div class="ttypography"><p>Realy impressive solution. I'm surprised no stars were given to you until me. Maybe many people didn't get your idea since the solution is actually much more complicated than your brief comment(at least in my opinion). I also wrote a piece of code which used your method but simplified a small part of steps. <a href="https://codeforces.com/contest/1540/submission/127317031">Here</a> it is.</p></div> </div> </div> <div class="reply info"> <a class="comment-834051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-834051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-834051"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="837924" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Harolinch" style="position: relative;"> <img src='https://userpic.codeforces.org/427341/avatar/cf8608aeb55edc95.jpg'/> </a> <div><a href="/profile/Harolinch" title="Pupil Harolinch" class="rated-user user-green">Harolinch</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837924" href="?#comment-837924" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837924" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="427341" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837924"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a> in problem Tree array you said that Fixing a given root r, the expected value of the entire process is obviously the sum of the expected values for a fixed root divided by n.</p><p>why we divide by n at the end ? </p></div> </div> </div> <div class="reply info"> <a class="comment-837924 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837924 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837924"> <li> <div class="comment"> <table class="comment-table" commentId="837928" commentParentId="837924"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837928" href="?#comment-837928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-837924" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837928" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837928"> <div class="moveup"> <div class="ttypography"><p>The calculation is independent based on whichever node that you choose first (it becomes the “root”). Initially you choose one of $$$n$$$ nodes with equal probability so you divide by $$$n$$$ at the end after you’ve summed up the independent expected value after choosing the node $$$i$$$ initially.</p></div> </div> </div> <div class="reply info"> <a class="comment-837928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837928"> </ul> </div> </li> </ul> </div> <br/> <div id="editBox-100805" 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 firstPreview100805 = true; var lastPreviewContent100805 = ''; 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=100805] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=100805] 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-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, 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:33:28</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:'81289372dffb0c4e',t:'MTY5NjcwNzIwOC45MzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1540D
1540
D
ru
D. Инвертируем инверсии
<div class="problem-statement"><div class="header"><div class="title">D. Инвертируем инверсии</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы играли со своей перестановкой $$$p$$$ длины $$$n$$$, но потеряли ее в Блэр, штат Алабама!</p><p>К счастью, вы помните некоторую информацию о перестановке. А точнее, вы помните массив $$$b$$$ длины $$$n$$$, где $$$b_i$$$ — это количество индексов $$$j$$$ таких, что $$$j &lt; i$$$ и $$$p_j &gt; p_i$$$.</p><p>У вас есть массив $$$b$$$, и вы хотите восстановить перестановку $$$p$$$. Однако ваша память не идеальна, и вы постоянно меняете значения массива $$$b$$$, как вспоминаете что-то еще. В следующие $$$q$$$ секунд каждую секунду происходит одно из следующего:</p><ol> <li> $$$1$$$ $$$i$$$ $$$x$$$ — вы вспоминаете, что $$$b_i$$$ равно $$$x$$$; </li><li> $$$2$$$ $$$i$$$ — вам нужно определить значение элемента $$$p_i$$$. Если существует более одного ответа, выведите любой. Можно доказать, что при данных ограничениях всегда найдется хотя бы одна перестановка. </li></ol><p>Отвечайте на запросы, и вы сможете вспомнить массив!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — размер перестановки.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$b_1, b_2 \ldots, b_n$$$ ($$$0 \leq b_i &lt; i$$$) — то, как вы помнили массив $$$b$$$ сначала.</p><p>В третьей строке задано одно целое число $$$q$$$ ($$$1 \leq q \leq 10^5$$$) — количество запросов.</p><p>В следующих $$$q$$$ строках заданы сами запросы, каждый одного из следующих видов: </p><ul> <li> $$$1$$$ $$$i$$$ $$$x$$$ ($$$0 \leq x &lt; i \leq n$$$) описывает запрос вида $$$1$$$; </li><li> $$$2$$$ $$$i$$$ ($$$1 \leq i \leq n$$$), описывает запрос вида $$$2$$$. </li></ul><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> 3 0 0 0 7 2 1 2 2 2 3 1 2 1 2 1 2 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 3 2 1 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 0 1 2 3 4 15 2 1 2 2 1 2 1 2 2 2 3 2 5 1 3 0 1 4 0 2 3 2 4 2 5 1 4 1 2 3 2 4 2 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 4 4 3 1 4 5 1 5 4 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере первоначально есть ровно одна перестановка, удовлетворяющая условиям: $$$[1, 2, 3]$$$, так как должна содержать $$$0$$$ инверсий.</p><p>После запроса вида $$$1$$$ массив $$$b$$$ становится равен $$$[0, 1, 0]$$$. Единственная перестановка $$$p$$$, порождающая данный массив — это $$$[2, 1, 3]$$$. В этой перестановке $$$b_2$$$ равен $$$1$$$, так как $$$p_1 &gt; p_2$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="a8b1eff70029eb19796e9a559ee79a2e"/> <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="73d6e96a98bbd7625389194b3afaf471bd9b24fb"/> <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='a8b1eff70029eb19796e9a559ee79a2e'>&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%2F1540%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='a8b1eff70029eb19796e9a559ee79a2e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1540">Codeforces Round 728 (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='a8b1eff70029eb19796e9a559ee79a2e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1540/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='a8b1eff70029eb19796e9a559ee79a2e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1027090"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a8b1eff70029eb19796e9a559ee79a2e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1027090"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92093" title="Codeforces Round #728" target="_blank">Codeforces Round #728 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13928" resourceName="Codeforces Round #728" resourceManual="true" src="//codeforces.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/92199" title="Tutorial" target="_blank">Tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13942" 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/1540">Задачи</a></li> <li><a href="/contest/1540/submit">Отослать</a></li> <li><a href="/contest/1540/my">Мои посылки</a></li> <li><a href="/contest/1540/status">Статус</a></li> <li><a href="/contest/1540/hacks">Взломы</a></li> <li><a href="/contest/1540/room/1">Комната</a></li> <li><a href="/contest/1540/standings">Положение</a></li> <li><a href="/contest/1540/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c691b6d99f561c254ebef60033f463943ff4330a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Инвертируем инверсии</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы играли со своей перестановкой $$$p$$$ длины $$$n$$$, но потеряли ее в Блэр, штат Алабама!</p><p>К счастью, вы помните некоторую информацию о перестановке. А точнее, вы помните массив $$$b$$$ длины $$$n$$$, где $$$b_i$$$ — это количество индексов $$$j$$$ таких, что $$$j &lt; i$$$ и $$$p_j &gt; p_i$$$.</p><p>У вас есть массив $$$b$$$, и вы хотите восстановить перестановку $$$p$$$. Однако ваша память не идеальна, и вы постоянно меняете значения массива $$$b$$$, как вспоминаете что-то еще. В следующие $$$q$$$ секунд каждую секунду происходит одно из следующего:</p><ol> <li> $$$1$$$ $$$i$$$ $$$x$$$ — вы вспоминаете, что $$$b_i$$$ равно $$$x$$$; </li><li> $$$2$$$ $$$i$$$ — вам нужно определить значение элемента $$$p_i$$$. Если существует более одного ответа, выведите любой. Можно доказать, что при данных ограничениях всегда найдется хотя бы одна перестановка. </li></ol><p>Отвечайте на запросы, и вы сможете вспомнить массив!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — размер перестановки.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$b_1, b_2 \ldots, b_n$$$ ($$$0 \leq b_i &lt; i$$$) — то, как вы помнили массив $$$b$$$ сначала.</p><p>В третьей строке задано одно целое число $$$q$$$ ($$$1 \leq q \leq 10^5$$$) — количество запросов.</p><p>В следующих $$$q$$$ строках заданы сами запросы, каждый одного из следующих видов: </p><ul> <li> $$$1$$$ $$$i$$$ $$$x$$$ ($$$0 \leq x &lt; i \leq n$$$) описывает запрос вида $$$1$$$; </li><li> $$$2$$$ $$$i$$$ ($$$1 \leq i \leq n$$$), описывает запрос вида $$$2$$$. </li></ul><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> 3 0 0 0 7 2 1 2 2 2 3 1 2 1 2 1 2 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 3 2 1 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 0 1 2 3 4 15 2 1 2 2 1 2 1 2 2 2 3 2 5 1 3 0 1 4 0 2 3 2 4 2 5 1 4 1 2 3 2 4 2 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 4 4 3 1 4 5 1 5 4 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере первоначально есть ровно одна перестановка, удовлетворяющая условиям: $$$[1, 2, 3]$$$, так как должна содержать $$$0$$$ инверсий.</p><p>После запроса вида $$$1$$$ массив $$$b$$$ становится равен $$$[0, 1, 0]$$$. Единственная перестановка $$$p$$$, порождающая данный массив — это $$$[2, 1, 3]$$$. В этой перестановке $$$b_2$$$ равен $$$1$$$, так как $$$p_1 &gt; p_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 11:29: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:'8124c6e05f371607',t:'MTY5NjY2NzM3MS42NzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3200"]
https://codeforces.com/blog/entry/92199
<!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="ea33d124a1ff874ace73f937748d303e"/> <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="Codeforces Round #728 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #728 Editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='ea33d124a1ff874ace73f937748d303e'>&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%2F92199">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='ea33d124a1ff874ace73f937748d303e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:31:32</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:31:32</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='ea33d124a1ff874ace73f937748d303e'/> <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/PurpleCrayon">PurpleCrayon</a></li> <li class="current selectedLava"><a href="/blog/PurpleCrayon">Blog</a></li> <li><a href="/teams/with/PurpleCrayon">Teams</a></li> <li><a href="/submissions/PurpleCrayon">Submissions</a></li> <li><a href="/groups/with/PurpleCrayon">Groups</a></li> <li><a href="/contests/with/PurpleCrayon">Contests</a></li> <li><a href="/contests/writer/PurpleCrayon">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/PurpleCrayon" style="text-decoration:none;color:black !important;">PurpleCrayon's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="92809"> <div class="title"> <a href="/blog/entry/92199"> <p>Codeforces Round #728 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a>, <a href="/topic/92809/en10">history</a>, <span class="format-humantime" title="Jun/25/2021 20:44">2 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><a href="/contest/1541/problem/A" title="Codeforces Round 728 (Div. 2)">1541A - Pretty Permutations</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The parity (whether $$$n$$$ is odd or even) matters.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Swapping two adjacent cats keeps both of them close to their original location and changes both of their locations.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>If $$$n$$$ is even, the optimal distance is $$$n$$$, and if $$$n$$$ is odd the optimal distance is $$$n+1$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541A">Tutorial is loading...</div></div></div><p><a href="/contest/1541/problem/B" title="Codeforces Round 728 (Div. 2)">1541B - Pleasant Pairs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>$$$i+j \leq 2 \cdot n$$$</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The number of pairs $$$(a, b)$$$ such that $$$a \cdot b \leq x$$$ is $$$O(x log x)$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/A" title="Codeforces Round 728 (Div. 1)">1540A - Great Graphs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What's the minimum value that an edge from $$$a$$$ to $$$b$$$ can be?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use edges with negative value whenever you can.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The sum of the values of edges with positive weight must be $$$\geq$$$ the maximum value in the array.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540A">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Tree Array</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Fix the initial node chosen and root the tree there, what is the contribution of each pair of nodes?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Nothing matters besides the path from node $$$a$$$ to node $$$b$$$, and the initially chosen node $$$r$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>You are given two stacks of size $$$a_1$$$ and $$$a_2$$$. In a single step, you randomly choose a stack to remove a single item from. What is the probability that $$$a_1$$$ becomes $$$0$$$ before $$$a_2$$$? Can you extend this argument for an arbitrary probability $$$p$$$ to remove from one of the two stacks, and a probability of $$$1-2p$$$ to do nothing?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/C2" title="Codeforces Round 728 (Div. 1)">1540C2 - Converging Array (Hard Version)</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What are the invariants? The monovariants?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What is the prefix sum array of the converged array? What is the difference array of the converged array?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you conducted the process on a prefix of size $$$1$$$, then of size $$$2$$$, and on and on?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How many values $$$x$$$ are actually interesting?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540C2">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Inverse Inversions</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The answer is always unique.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Try to figure out what the location of the $$$i$$$-th element would be if you only looked at the first $$$i$$$ elements, then the first $$$i+1$$$, etc. to find an $$$O(nq)$$$ solution.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use sqrt decomposition to optimize it.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540D">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/E" title="Codeforces Round 728 (Div. 1)">1540E - Tasty Dishes</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How much does each chef's initial dish contribute at time $$$k$$$?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you really, really wanted to use matrix exponentiation?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How can you multiply some vectors by a matrix in $$$O(N)$$$ time? (go back to linear algebra class)</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Decompose into linear combinations of eigenvectors.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540E">Tutorial is loading...</div></div></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/1540" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 1)</a> </span> </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/1541" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-191295-92809").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "191295", blogEntryId: "92199", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-92809"><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'>+96</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-92809"><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/PurpleCrayon"><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/PurpleCrayon"> PurpleCrayon </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="Jun/25/2021 20:44">2 years ago</span> </li> <li> <a href="/blog/entry/92199#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/92199#comments"> 170 </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="100805"> <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 (136)</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="808750" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808750" href="?#comment-808750" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808750" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-66" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-66</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808750"> <div class="moveup"> <div class="ttypography"><p>PURPLECRAYON ORZ</p></div> </div> </div> <div class="reply info"> <a class="comment-808750 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808750 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808750"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808751" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hbarp" style="position: relative;"> <img src='https://userpic.codeforces.org/1387715/avatar/c727a810db6ffb66.jpg'/> </a> <div><a href="/profile/hbarp" title="Candidate Master hbarp" class="rated-user user-violet">hbarp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808751" href="?#comment-808751" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808751" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="1387715" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-83</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808751"> <div class="moveup"> <div class="ttypography"><p>Damn, so orz round. <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Мастер PurpleCrayon">PurpleCrayon</a> orz</p></div> </div> </div> <div class="reply info"> <a class="comment-808751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808751"> <li> <div class="comment"> <table class="comment-table" commentId="808805" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/naman1601" style="position: relative;"> <img src='https://userpic.codeforces.org/1703219/avatar/d63fc523dc05fda8.jpg'/> </a> <div><a href="/profile/naman1601" title="Master naman1601" class="rated-user user-orange">naman1601</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808805" href="?#comment-808805" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808805" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-51" data-commentUserId="1703219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-51</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808805"> <div class="moveup"> <div class="ttypography"><p>yeah, amazing problemset, not speedforces at all :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808805 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808805 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808805"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808817" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LOVELY_BOY_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/LOVELY_BOY_" title="Newbie LOVELY_BOY_" class="rated-user user-gray">LOVELY_BOY_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808817" href="?#comment-808817" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-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="808817" 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="808817" class="CommentVoteFrame" data-commentRating="35" data-commentUserId="2089809" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808817"> <div class="moveup"> <div class="ttypography"><p>LOL <a class="rated-user user-blue" href="/profile/hbarp" title="Эксперт hbarp">hbarp</a>,even you didn't participate in the contest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808817 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808817 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808817"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808753" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DontLookBack" style="position: relative;"> <img src='https://userpic.codeforces.org/1534766/avatar/4eacdc5f9758fc28.jpg'/> </a> <div><a href="/profile/DontLookBack" title="Specialist DontLookBack" class="rated-user user-cyan">DontLookBack</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808753" href="?#comment-808753" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808753" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1534766" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808753"> <div class="moveup"> <div class="ttypography"><p>I am curious, how many div2 testers solved D?</p></div> </div> </div> <div class="reply info"> <a class="comment-808753 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808753 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808753"> <li> <div class="comment"> <table class="comment-table" commentId="808826" commentParentId="808753"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/highonjuice" style="position: relative;"> <img src='https://userpic.codeforces.org/1457566/avatar/f7988dd2af03d38b.jpg'/> </a> <div><a href="/profile/highonjuice" title="Pupil highonjuice" class="rated-user user-green">highonjuice</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808826" href="?#comment-808826" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808753" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808826" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1457566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808826"> <div class="moveup"> <div class="ttypography"><p>like 2 ppl, it was hard for me</p></div> </div> </div> <div class="reply info"> <a class="comment-808826 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808826 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808826"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808757" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tlatoani" style="position: relative;"> <img src='https://userpic.codeforces.org/614001/avatar/598b4e8358aad1b4.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/Tlatoani" title="Grandmaster Tlatoani" class="rated-user user-red">Tlatoani</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:18">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808757" href="?#comment-808757" style="font-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="808757" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="808757" class="CommentVoteFrame" data-commentRating="121" data-commentUserId="614001" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+121</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808757"> <div class="moveup"> <div class="ttypography"><h4>Alternate solution to <a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Инвертируем инверсии</a></h4><p>(Read the first nontrivial paragraph of the editorial before reading this alternate solution)</p><p>Let $$$p_r(k) = x$$$ denote that of the numbers $$$p(1), \ldots, p(r)$$$ in sorted order, $$$p(k)$$$ is equal to the $$$x$$$th of these numbers. We will take a decomposition strategy just as the editorial does, though our strategy will be different. We will divide $$$[1, n]$$$ into blocks of length $$$b$$$. For each block covering some interval $$$[l, r]$$$, we will store $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>This means that for any $$$k$$$, if we know $$$p_r(k)$$$ for some block $$$[l, r]$$$, then we can determine $$$p_{r'}(k)$$$ for the block $$$[l', r']$$$ immediately to the right by binary searching on the numbers stored for $$$[l', r']$$$. Therefore, we can perform queries in $$$O\left(\frac n b \lg b\right)$$$.</p><p>We now need to figure out updates. There are probably simple ways to perform updates in $$$O(b\lg b)$$$, but this yields an overall runtime of $$$O(q\sqrt n \lg n)$$$ which is too slow.</p><p>Therefore, we can instead store each block as a segment tree. For each range $$$[l, r]$$$ in the segment tree we store the same thing we store for the whole block: $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>We then have to quickly merge two intervals. We can merge two intervals of length $$$\lambda$$$ in $$$O(\lambda \lg \lambda)$$$ by doing binary search just as we did above, but this still only yields $$$O(b\lg b)$$$ update overall. However, these $$$\lambda$$$ binary searches can be optimized using two pointers to $$$O(\lambda)$$$, making the overall update $$$O(b)$$$.</p><p>We thus have $$$O\left(\frac n b \lg b\right)$$$ query and $$$O(b)$$$ update. Therefore, we can choose $$$b = \sqrt{n\lg n}$$$ to attain an overall runtime of $$$O\left(q\sqrt{n\lg n}\right)$$$ just as the editorial does.</p><p><a href="https://codeforces.com/contest/1540/submission/120611645">Submission in Kotlin</a></p><p><a href="https://codeforces.com/contest/1540/submission/120612729">Submission in C++</a></p><p>It is interesting to note that this solution is quite fast. At the time of writing this update, the C++ version is the fastest correct submission (and runs under 1 second!) and the Kotlin version is faster than the vast majority of submissions.</p></div> </div> </div> <div class="reply info"> <a class="comment-808757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808757"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808765" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardcode229" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardcode229" title="Newbie hardcode229" class="rated-user user-gray">hardcode229</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808765" href="?#comment-808765" style="font-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="808765" 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="808765" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1635180" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808765"> <div class="moveup"> <div class="ttypography"><p>The 3rd hint for the second problem is same as that of the first problem, is it related or a mistake? <strong>UPD:</strong> it is corrected.</p></div> </div> </div> <div class="reply info"> <a class="comment-808765 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808765 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808765"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808769" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/peanut" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/peanut" title="Specialist peanut" class="rated-user user-cyan">peanut</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:24">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808769" href="?#comment-808769" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808769" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="1167233" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+22</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808769"> <div class="moveup"> <div class="ttypography"><p>speedforces.</p></div> </div> </div> <div class="reply info"> <a class="comment-808769 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808769 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808769"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808781" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/graphs_11" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/graphs_11" title="Specialist graphs_11" class="rated-user user-cyan">graphs_11</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808781" href="?#comment-808781" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808781" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1610110" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808781"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">Problem B Detailed Explanation</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808781 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808781 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808781"> <li> <div class="comment"> <table class="comment-table" commentId="809069" commentParentId="808781"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:40">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809069" href="?#comment-809069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808781" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809069" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809069"> <div class="moveup"> <div class="ttypography"><p>Thank you, very well explained</p></div> </div> </div> <div class="reply info"> <a class="comment-809069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809069"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808790" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PC_E1052" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PC_E1052" title="Pupil PC_E1052" class="rated-user user-green">PC_E1052</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808790" href="?#comment-808790" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808790" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="811219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808790"> <div class="moveup"> <div class="ttypography"><p>c was too easy, d was too hard. but d was very nice problem though. </p></div> </div> </div> <div class="reply info"> <a class="comment-808790 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808790 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808790"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808793" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808793" href="?#comment-808793" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808793" class="CommentVoteFrame" data-commentRating="58" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+58</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808793"> <div class="moveup"> <div class="ttypography"><p>Paging <a class="rated-user user-legendary" href="/profile/ecnerwala" title="Легендарный гроссмейстер ecnerwala"><span class="legendary-user-first-letter">e</span>cnerwala</a> to explain his solution to D1E if he'd like. It seems offline?</p></div> </div> </div> <div class="reply info"> <a class="comment-808793 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808793 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808793"> <li> <div class="comment"> <table class="comment-table" commentId="808979" commentParentId="808793"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ecnerwala" 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/ecnerwala" title="Legendary Grandmaster ecnerwala" class="rated-user user-legendary"><span class="legendary-user-first-letter">e</span>cnerwala</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808979" href="?#comment-808979" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808793" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808979" class="CommentVoteFrame" data-commentRating="40" data-commentUserId="57502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808979"> <div class="moveup"> <div class="ttypography"><p>My solution is $$$O(K N^3 + QN)$$$. I just precomputed the coefficient of each $$$a_i$$$ for each prefix-range for each number of days since person $$$i$$$ becomes positive (only $$$1000$$$ possible days) in $$$O(N \cdot K \cdot N^2)$$$, and then summed up the appropriate ones to answer each query in $$$O(N)$$$. It's written in the offline style to use only $$$O(KN)$$$ memory at a time (grouped by $$$a_i$$$) instead of $$$O(KN^2)$$$.</p><p>My passing submission is just $$$KN^3 / 6$$$ instead of the $$$KN^3$$$ I submitted in contest :'(</p><p>If you guys wanted to prevent this, $$$K$$$ could've been much higher, like $$$1e18$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808979 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808979 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808979"> <li> <div class="comment"> <table class="comment-table" commentId="809002" commentParentId="808979"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809002" href="?#comment-809002" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808979" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809002" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809002"> <div class="moveup"> <div class="ttypography"><p>:( I knew of this solution (it’s why ML is tight) but I didn’t realize that it could be done offline with small memory. Of course $$$K$$$ higher is obvious solution but main issue is that the extra modulos from binary exponentiation make it very hard to pass in Java without allowing other unoptimal solutions through such as precomputing inverses of the matrix. Probably $$$k=10^5$$$ would’ve been a better choice. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-809002 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809002 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809002"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808795" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zukonit14" style="position: relative;"> <img src='https://userpic.codeforces.org/1192187/avatar/5afd49be87fb87d9.jpg'/> </a> <div><a href="/profile/zukonit14" title="Expert zukonit14" class="rated-user user-blue">zukonit14</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808795" href="?#comment-808795" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808795" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1192187" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808795"> <div class="moveup"> <div class="ttypography"><p>Does Div2 D deserved to be D Problem? According to me it should've been Div2 E.</p></div> </div> </div> <div class="reply info"> <a class="comment-808795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808795"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808796" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mangat_angad" style="position: relative;"> <img src='https://userpic.codeforces.org/1449578/avatar/d3cadb0c26e0c11f.jpg'/> </a> <div><a href="/profile/mangat_angad" title="Specialist mangat_angad" class="rated-user user-cyan">mangat_angad</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808796" href="?#comment-808796" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808796" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1449578" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808796"> <div class="moveup"> <div class="ttypography"><p>I feel like such an idiot for not being able to understand problem C (Div2). For some reason I thought the nodes were connected like this — 1-&gt;2-&gt;3-&gt;....-&gt;N and that we had to minimise answer by adding other edges (of negative weight in case they dont give a negative cycle) to this graph.</p></div> </div> </div> <div class="reply info"> <a class="comment-808796 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808796 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808796"> <li> <div class="comment"> <table class="comment-table" commentId="808896" commentParentId="808796"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808896" href="?#comment-808896" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808796" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808896" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808896"> <div class="moveup"> <div class="ttypography"><p>But that's exactly what I did, and the final answer is the sum of the array — sum of all subarrays. <a href="https://codeforces.com/contest/1541/submission/120611950">120611950</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808896 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808896 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808896"> <li> <div class="comment"> <table class="comment-table" commentId="808941" commentParentId="808896"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808941" href="?#comment-808941" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808896" style="font-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="808941" 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="808941" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808941"> <div class="moveup"> <div class="ttypography"><p>No, that's not what you did. To compute the answer via the method described above, you would have to compute how many elements are lesser than the current element at any given iteration and add them and also keep and their count using a Fenwick tree/ BIT. That's the incorrect approach though because sorting would be more optimal.</p></div> </div> </div> <div class="reply info"> <a class="comment-808941 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808941 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808941"> <li> <div class="comment"> <table class="comment-table" commentId="808952" commentParentId="808941"> <tr> <td class="left"> <div style="position: absolute; left: 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/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808952" href="?#comment-808952" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808941" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808952" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808952"> <div class="moveup"> <div class="ttypography"><p>Sorry if I misunderstood things. mangat_angad only mentioned adding negative weighed edges to the 1-&gt;2-&gt;3-&gt;...N graph, which is what I thought to arrive at my solution. The array I mentioned is indeed sorted and formed by distance differences which are the weights in the 1-&gt;2-&gt;3-&gt;...N graph. Unfortunately I'm still too noob to understand the tree structures you mentioned.</p></div> </div> </div> <div class="reply info"> <a class="comment-808952 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808952 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808952"> <li> <div class="comment"> <table class="comment-table" commentId="808955" commentParentId="808952"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808955" href="?#comment-808955" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808952" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808955" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808955"> <div class="moveup"> <div class="ttypography"><p>Nothing unfortunate about it, logic trumps everything </p></div> </div> </div> <div class="reply info"> <a class="comment-808955 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808955 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808955"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808797" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808797" href="?#comment-808797" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808797" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808797"> <div class="moveup"> <div class="ttypography"><p>Just want to apologize to authors for the stupidest question, I misread the task..</p></div> </div> </div> <div class="reply info"> <a class="comment-808797 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808797 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808797"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808813" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808813" href="?#comment-808813" style="font-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="808813" 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="808813" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808813"> <div class="moveup"> <div class="ttypography"><p>Can someone tell me the meaning of this line in problem Div2D/Div1B<br /></p> <blockquote><p>Note that, until reaching, l every possible process still has the same probability of reaching b before a. Therefore, we can assume that the process has reached l and calculate the probability from there.</p> </blockquote><p>What same probability are they talking about?</p></div> </div> </div> <div class="reply info"> <a class="comment-808813 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808813 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808813"> <li> <div class="comment"> <table class="comment-table" commentId="808831" commentParentId="808813"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808831" href="?#comment-808831" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808813" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808831" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808831"> <div class="moveup"> <div class="ttypography"><p>Here's what it's trying to say:</p><p>Suppose we start by marking the root. To mark a or b, we must first mark the lca, so we may assume that the lca has just been marked.</p></div> </div> </div> <div class="reply info"> <a class="comment-808831 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808831 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808831"> <li> <div class="comment"> <table class="comment-table" commentId="808840" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808840" href="?#comment-808840" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808840" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808840"> <div class="moveup"> <div class="ttypography"><p>And what does this line mean? <em>&quot;The problem can be rephrased as having two stacks of size dist(l,a) and dist(l,b) with an arbitrary p to remove a node from one of the two stack (and 1−2p to nothing) and finding the probability that dist(l,b) reaches zero before dist(l,a).&quot;</em></p></div> </div> </div> <div class="reply info"> <a class="comment-808840 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808840 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808840"> <li> <div class="comment"> <table class="comment-table" commentId="808857" commentParentId="808840"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808857" href="?#comment-808857" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808840" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808857" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808857"> <div class="moveup"> <div class="ttypography"><p>Once you've reached the lca $$$l$$$, in a single step you either step closer to $$$a$$$, step closer to $$$b$$$, or step closer to neither.</p></div> </div> </div> <div class="reply info"> <a class="comment-808857 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808857 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808857"> <li> <div class="comment"> <table class="comment-table" commentId="808862" commentParentId="808857"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808862" href="?#comment-808862" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808857" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808862" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808862"> <div class="moveup"> <div class="ttypography"><p>Can you add implementation for this problem please?</p></div> </div> </div> <div class="reply info"> <a class="comment-808862 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808862 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808862"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808849" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808849" href="?#comment-808849" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808849" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808849"> <div class="moveup"> <div class="ttypography"><p>So, we mark lca first (of course). But why wouldn't it affect the final probability of reaching b before a? I mean, why is it sufficient to calculate the probability after marking lca?</p></div> </div> </div> <div class="reply info"> <a class="comment-808849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808849"> <li> <div class="comment"> <table class="comment-table" commentId="808873" commentParentId="808849"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808873" href="?#comment-808873" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808849" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808873" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808873"> <div class="moveup"> <div class="ttypography"><p>Before marking the lca, there is no way to make more progress towards $$$b$$$ than $$$a$$$ or vice versa. The subset of marked vertices also does not change the probability of moving towards $$$a$$$ or $$$b$$$ after reaching the lca because we're choosing uniformly at random and exactly two vertices are of interest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808873 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808873 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808873"> <li> <div class="comment"> <table class="comment-table" commentId="808883" commentParentId="808873"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808883" href="?#comment-808883" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808873" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808883" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808883"> <div class="moveup"> <div class="ttypography"><p>Now I get it. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808883 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808883 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808883"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808814" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808814" href="?#comment-808814" style="font-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="808814" 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="808814" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808814"> <div class="moveup"> <div class="ttypography"><p>So, my Solution for <strong>Div1 Problem B</strong> / <strong>Div2 Problem D</strong> / <strong>1540B — Tree Array</strong>:</p><p>Chose two Nodes $$$A$$$ and $$$B$$$ with $$$A&gt;B$$$. </p><p><strong>First DFS:</strong> Find the path from $$$A$$$ to $$$B$$$. I call it $$$path_p$$$. On $$$path_p$$$ mark the distance to $$$B$$$ for each node. </p><p><strong>Second DFS:</strong> For each remaining node $$$N$$$ find the shortest path to $$$path_p$$$. It will hit it at some node of the $$$path_p$$$ which has some distance $$$D$$$ marked on it. We mark $$$N$$$ with $$$D$$$. (See comment below for image.)</p><p><strong>Calculation:</strong> For each node $$$N$$$ we can calculate $$$P_i$$$. $$$P_i$$$ is the probability to reach Node $$$B$$$ before we reach Node $$$A$$$. We sum $$$P_i$$$ for each node. $$$P_i$$$ is also the probability, that the pair of Nodes $$$A$$$ and $$$B$$$ with starting node $$$N$$$ will contribute to the inversion sum. </p><p><strong>Iteration:</strong> We need to repeat this for each pair $$$A$$$ and $$$B$$$. In the end we divide the answer by $$$n$$$, the amount of nodes (the probability to start with Node $$$N$$$). </p><p>This algorithm is $$$O(N^3)$$$. See my Solution <a href="/contest/1540/submission/120603369" title="Посылка 120603369 от OleschY">120603369</a></p> <div class="spoiler"><b class="spoiler-title">How to calculate P_i</b><div class="spoiler-content" style="display: none;"><p>I wrote myself a small helper DP-program to find the regularities. Let $$$D$$$ be the Distance between $$$A$$$ and $$$B$$$ and $$$d$$$ be the distance from the node $$$N$$$ to $$$B$$$. My educated guess was: $$$P_i=\frac{\sum_{i=0}^{d-1}\binom{D-1}{i} }{2^{D-1}}$$$</p> <div class="spoiler"><b class="spoiler-title">Helper Program</b><div class="spoiler-content" style="display: none;"><p>It checks for a path of some length for each Intervall $$$[A,B]$$$ which is already visited, what the probability to reach one node before the other is. </p> <pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; int solve(int n) { vector&lt;vector&lt;double&gt;&gt; dp(n, vector&lt;double&gt;(n, 0)); for(int i = 0; i &lt; n; ++i) { dp[0][i] = 1; dp[i][n - 1] = 0; } dp[0][n - 1] = -1; for(int w = n; w &gt;= 0; w--) { for(int i = 1; i + w &lt; n - 1; i++) { int l = i; int r = w + i; dp[l][r] = 0.5 * (dp[l - 1][r] + dp[l][r + 1]); } } cout &lt;&lt; n &lt;&lt; &quot;\n\n&quot;; for(int i = 0; i &lt; n; i++) { cout &lt;&lt; dp[i][i]*(1&lt;&lt;(n-2)) &lt;&lt; &quot;\n&quot;; } cout &lt;&lt; &quot;\n\n\n\n&quot;; return 0; } //====================== // Technical stuff //====================== int main() { int ntest = 12; for(int test = 2; test &lt; ntest; ++test) { solve(test); } return 0; } </code></pre></div></div></div></div></div> </div> </div> <div class="reply info"> <a class="comment-808814 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808814 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808814"> <li> <div class="comment"> <table class="comment-table" commentId="808843" commentParentId="808814"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808843" href="?#comment-808843" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808814" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808843" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808843"> <div class="moveup"> <div class="ttypography"><p>Can you explain your solution in a little bit more detail? :')</p></div> </div> </div> <div class="reply info"> <a class="comment-808843 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808843 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808843"> <li> <div class="comment"> <table class="comment-table" commentId="808869" commentParentId="808843"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808869" href="?#comment-808869" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808843" style="font-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="808869" 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="808869" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808869"> <div class="moveup"> <div class="ttypography"><p>Oof, I can give you an image, that shows how the distances from the two DFS are distributed on an example. You can see Nodes $$$A$$$ and $$$B$$$ and the numbers are the distances we write into the nodes. </p><p><img alt=" " src="/predownloaded/d8/2f/d82f98ecd2c1b4bd15b3c40e62476f6ae2741a64.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>If you have specific questions about some steps go ahead and ask. </p></div> </div> </div> <div class="reply info"> <a class="comment-808869 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808869 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808869"> <li> <div class="comment"> <table class="comment-table" commentId="810069" commentParentId="808869"> <tr> <td class="left"> <div style="position: absolute; left: 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/Mrajaryan" style="position: relative;"> <img src='https://userpic.codeforces.org/1377953/avatar/e904b3a3a2eac1ad.jpg'/> </a> <div><a href="/profile/Mrajaryan" title="Newbie Mrajaryan" class="rated-user user-gray">Mrajaryan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 15:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810069" href="?#comment-810069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808869" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810069" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1377953" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810069"> <div class="moveup"> <div class="ttypography"><p>what does the dp states mean in your helper program? I am unable to understand. Can you please explain?</p></div> </div> </div> <div class="reply info"> <a class="comment-810069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810069"> <li> <div class="comment"> <table class="comment-table" commentId="810097" commentParentId="810069"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 18:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810097" href="?#comment-810097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-810069" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810097"> <div class="moveup"> <div class="ttypography"><p>You have Nodes $$$1$$$ through $$$N$$$, neighbouring IDs are connected. The state $$$dp[l][r]$$$ is the probability, that node $$$N$$$ will be reached before node $$$1$$$ with all the nodes $$$l$$$ through $$$r$$$ marked already. Obviously $$$dp[1][x]=0$$$ and $$$dp[x][N]=1$$$ ($$$dp[1][N]$$$ can't happen). The recurrence is $$$dp[l][r]=(dp[l-1][r]+dp[l][r+1])/2$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-810097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808818" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808818" href="?#comment-808818" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808818" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808818"> <div class="moveup"> <div class="ttypography"><p>I can't grasp the editorial of Div 2 D/ Div 1 B. Can somebody provide a more intuitive explanation?</p></div> </div> </div> <div class="reply info"> <a class="comment-808818 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808818 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808818"> <li> <div class="comment"> <table class="comment-table" commentId="808821" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:45">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808821" href="?#comment-808821" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808821" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808821"> <div class="moveup"> <div class="ttypography"><p>same :(</p></div> </div> </div> <div class="reply info"> <a class="comment-808821 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808821 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808821"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808861" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808861" href="?#comment-808861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808861" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808861"> <div class="moveup"> <div class="ttypography"><p>Step 1. use linearity of expectation. The answer is</p> <center>$$$\sum_{a&lt;b} P(b\text{ appears before }a). $$$</center><p>Step 2: Observe that if we start by marking a vertex $$$c$$$ on the path between $$$a$$$ and $$$b$$$, and suppose the next marked vertex on the path is $$$d$$$. Then, the probability that $$$d$$$ is between $$$c$$$ and $$$a$$$ and the probability that $$$d$$$ is between $$$c$$$ and $$$b$$$ are both $$$1/2$$$. This is because there are only two choices for $$$d$$$ and we're choosing uniformly at random. This means that the answer only depends on $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p><p>Step 3: run a dp to calculate the probability that we mark $$$b$$$ before $$$a$$$ given $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808861"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808833" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808833" href="?#comment-808833" style="font-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="808833" 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="808833" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-72" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-72</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808833"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin &gt;&gt; t; while(t--){ int n; cin &gt;&gt; n; long long arr[n]; for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0; for(int i = 0; i &lt; n — 1; i++){ for(int j = arr[i] — 2 — i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } } } cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;; } return 0; }</p><p>/* Accepted code A different approach using arrays (as I don't know what vectors are, haven't read that) I hope this is a optimal approach. Any suggestions related to this are whole-heartedly welcomed. Also, please guide me how could I have optimized the code to a much extent. Thanks in advance! Keep programming! */</p></div> </div> </div> <div class="reply info"> <a class="comment-808833 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808833 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808833"> <li> <div class="comment"> <table class="comment-table" commentId="808844" commentParentId="808833"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808844" href="?#comment-808844" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808833" style="font-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="808844" 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="808844" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-35" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808844"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-808844 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808844 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808844"> <li> <div class="comment"> <table class="comment-table" commentId="808863" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808863" href="?#comment-808863" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808863" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808863"> <div class="moveup"> <div class="ttypography"><p>Not studied yet, I'm still a beginner, but planning to start soon. Thanks for the guidance.</p></div> </div> </div> <div class="reply info"> <a class="comment-808863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808863"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808879" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808879" href="?#comment-808879" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808879" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808879"> <div class="moveup"> <div class="ttypography"><p>once upon a time, I also did problems while not know what vectors are. sad times :'(</p></div> </div> </div> <div class="reply info"> <a class="comment-808879 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808879 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808879"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808926" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808926" href="?#comment-808926" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808926" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808926"> <div class="moveup"> <div class="ttypography"><p>There's no issue in not knowing vectors. Yes they are important I agree but not knowing vectors should not be discouraged. I became expert here without knowing anything about vectors plus he is a beginner so he shouldn't be discouraged like this.</p></div> </div> </div> <div class="reply info"> <a class="comment-808926 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808926 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808926"> <li> <div class="comment"> <table class="comment-table" commentId="808927" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Tech.Maniac" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Tech.Maniac" title="Expert Tech.Maniac" class="rated-user user-blue">Tech.Maniac</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808927" href="?#comment-808927" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808927" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1242860" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808927"> <div class="moveup"> <div class="ttypography"><p>+1, I agree with you. Same I was expert last year solely using arrays</p></div> </div> </div> <div class="reply info"> <a class="comment-808927 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808927 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808927"> <li> <div class="comment"> <table class="comment-table" commentId="809201" commentParentId="808927"> <tr> <td class="left"> <div style="position: absolute; left: 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/Yash.Amin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Yash.Amin" title="Specialist Yash.Amin" class="rated-user user-cyan">Yash.Amin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809201" href="?#comment-809201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808927" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809201" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-28" data-commentUserId="1226462" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-28</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809201"> <div class="moveup"> <div class="ttypography"><p>Bas kar bsdk kitna jhooth bolega</p></div> </div> </div> <div class="reply info"> <a class="comment-809201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809201"> <li> <div class="comment"> <table class="comment-table" commentId="809215" commentParentId="809201"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809215" href="?#comment-809215" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809215" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809215"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-blue" href="/profile/Yash.Amin" title="Эксперт Yash.Amin">Yash.Amin</a> Could you please refrain from using foul language on educational discussions. Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-809215 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809215 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809215"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808928" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808928" href="?#comment-808928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808928" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808928"> <div class="moveup"> <div class="ttypography"><p>Ah my bad, I did not want to come across as being arrogant, but I was genuinely confused that some people did not know vectors although they are using C++.</p></div> </div> </div> <div class="reply info"> <a class="comment-808928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808928"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808839" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamkiller04" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dreamkiller04" title="Newbie dreamkiller04" class="rated-user user-gray">dreamkiller04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808839" href="?#comment-808839" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2089608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808839"> <div class="moveup"> <div class="ttypography"><p>Please add implementations too.</p></div> </div> </div> <div class="reply info"> <a class="comment-808839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808839"> <li> <div class="comment"> <table class="comment-table" commentId="809106" commentParentId="808839"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809106" href="?#comment-809106" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808839" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809106" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809106"> <div class="moveup"> <div class="ttypography"><p>Simply running two loops and checking every case would give a TLE. So, we might want to minimize the number of operations. For this, we would only consider the cases where the sum of indices is a multiple of an element.</p><p>For this, we would first create two loops, one within the other, first loop iterating i from 0 to (n — 1) with an incrementation of 1. By observation, we can see that the first index for which the sum of indices will be a multiple of arr[i] is (arr[i] — 2 — i).</p><p>So, in the nested loop we will run j = (arr[i] — 2 — i) till (n — 1) with an incrementation of arr[i]. We would ignore the cases where j &lt; 0 or j &gt;= n.</p><p>Finally, we need to check for how many cases this holds (arr[i] * arr[j] = i + j + 2 and j &gt; i).</p><p>Suggestions are welcomed!</p></div> </div> </div> <div class="reply info"> <a class="comment-809106 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809106 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809106"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808842" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808842" href="?#comment-808842" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808842" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-64" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-64</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808842"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){</p><p>ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);</p><p>int t;</p><p>cin &gt;&gt; t;</p><p>while(t--){</p><p>int n;</p> <pre>cin &gt;&gt; n;</pre><p>long long arr[n];</p> <pre>for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0;</pre><p>for(int i = 0; i &lt; n — 1; i++){</p> <pre>for(int j = arr[i] &amp;mdash; 2 &amp;mdash; i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } }</pre><p>}</p><p>cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;;</p><p>}</p> <pre>return 0;</pre><p>}</p><p>/* Accepted code</p><p>A different approach using arrays (as I don't know what vectors are, haven't read that)</p><p>I hope this is a optimal approach.</p><p>Any suggestions related to this are whole-heartedly welcomed.</p><p>Also, please guide me how could I have optimized the code to a much extent.</p><p>Thanks in advance!</p><p>Keep programming! </p><p>*/</p></div> </div> </div> <div class="reply info"> <a class="comment-808842 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808842 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808842"> <li> <div class="comment"> <table class="comment-table" commentId="808851" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808851" href="?#comment-808851" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808851" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808851"> <div class="moveup"> <div class="ttypography"><p>Use spoilers for writing codes, please!</p></div> </div> </div> <div class="reply info"> <a class="comment-808851 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808851 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808851"> <li> <div class="comment"> <table class="comment-table" commentId="808870" commentParentId="808851"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808870" href="?#comment-808870" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808851" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808870" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808870"> <div class="moveup"> <div class="ttypography"><p>Actually, this is my first comment. Don't know much of this stuff as of now, but I'll surely take care of it the very next time.</p></div> </div> </div> <div class="reply info"> <a class="comment-808870 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808870 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808870"> <li> <div class="comment"> <table class="comment-table" commentId="809760" commentParentId="808870"> <tr> <td class="left"> <div style="position: absolute; left: 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/sus" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sus" title="Pupil sus" class="rated-user user-green">sus</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 05:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809760" href="?#comment-809760" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808870" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809760" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1749651" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809760"> <div class="moveup"> <div class="ttypography"><p>what problem is your code for</p></div> </div> </div> <div class="reply info"> <a class="comment-809760 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809760 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809760"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808884" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sevlll777" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sevlll777" title="Grandmaster sevlll777" class="rated-user user-red">sevlll777</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808884" href="?#comment-808884" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808884" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="839333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808884"> <div class="moveup"> <div class="ttypography"><p>NICE CODESTYLE!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-808884 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808884 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808884"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809084" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cj2021" style="position: relative;"> <img src='https://userpic.codeforces.org/1927237/avatar/b64ff59bd9dcf385.jpg'/> </a> <div><a href="/profile/cj2021" title="Newbie cj2021" class="rated-user user-gray">cj2021</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809084" href="?#comment-809084" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809084" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1927237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809084"> <div class="moveup"> <div class="ttypography"><p>What is &amp;mdash?</p><p>Just curious to know as haven't seen it before.</p></div> </div> </div> <div class="reply info"> <a class="comment-809084 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809084 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809084"> <li> <div class="comment"> <table class="comment-table" commentId="809097" commentParentId="809084"> <tr> <td class="left"> <div style="position: absolute; left: 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/klahsiv" style="position: relative;"> <img src='https://userpic.codeforces.org/1590145/avatar/1bf86ae3d48e55b.jpg'/> </a> <div><a href="/profile/klahsiv" title="Expert klahsiv" class="rated-user user-blue">klahsiv</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809097" href="?#comment-809097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809084" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590145" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809097"> <div class="moveup"> <div class="ttypography"><p>it is minus (-).</p></div> </div> </div> <div class="reply info"> <a class="comment-809097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808848" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/willy108" style="position: relative;"> <img src='https://userpic.codeforces.org/1439320/avatar/d7f79ed4e8b32e9a.jpg'/> </a> <div><a href="/profile/willy108" title="Master willy108" class="rated-user user-orange">willy108</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808848" href="?#comment-808848" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808848" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="1439320" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808848"> <div class="moveup"> <div class="ttypography"><p>Div2 B can also be done in O(NsqrtN). We know that for a given pair of indeces i+j &lt; 2n, so any pair that a[i] * a[j] &lt; 2n will have to have one of the two terms be &lt;= sqrt(n) (with some off by one errors of course). So the algorithm is to store an array of pairs [array value, index] and sort that array by the value. If the array value is &lt;= sqrt(2n) we can naively loop over the rest of the array in O(n) time and check (be careful about overcount), and if the value is &gt; sqrt(n), we can ignore it. This works since when a[i] * a[j] &lt; 2n one of a[i] or a[j] has to be &lt;= sqrt(2n) and as a result, every pair will be counted.</p></div> </div> </div> <div class="reply info"> <a class="comment-808848 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808848 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808848"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808860" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bcollet" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bcollet" title="Master bcollet" class="rated-user user-orange">bcollet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808860" href="?#comment-808860" style="font-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="808860" 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="808860" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="858059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808860"> <div class="moveup"> <div class="ttypography"><p>I don't understand in div1 C why it's prefix of b, in the case i=3 we have $$$a_1+a_2+a_3=f_1+f_1+b_1+f_1+b_1+b_2$$$ so $$$f_1=(ap_i-2b_1-b_2)$$$ I believe the general formula is something in the taste of $$$f_1=(ap_i-ibp_{i-1}+bpt_{i-1})/i$$$ where bpt_i=b_1+2b_2+...+ib_i, I think I miss something<br />Edit: corrected</p></div> </div> </div> <div class="reply info"> <a class="comment-808860 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808860 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808860"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808865" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ParsaS" style="position: relative;"> <img src='https://userpic.codeforces.org/1590150/avatar/dc2d8c002d2c5e1e.jpg'/> </a> <div><a href="/profile/ParsaS" title="Candidate Master ParsaS" class="rated-user user-violet">ParsaS</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808865" href="?#comment-808865" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808865" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590150" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808865"> <div class="moveup"> <div class="ttypography"><p>Nice problems. thanks for almost fast editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-808865 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808865 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808865"> <li> <div class="comment"> <table class="comment-table" commentId="808871" commentParentId="808865"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/E404_Not_Found" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/E404_Not_Found" title="Expert E404_Not_Found" class="rated-user user-blue">E404_Not_Found</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808871" href="?#comment-808871" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808865" style="font-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="808871" 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="808871" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1662858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808871"> <div class="moveup"> <div class="ttypography"><p>Yes thanks for fast editorial :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808871 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808871 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808871"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808890" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vikash_8090_b" style="position: relative;"> <img src='https://userpic.codeforces.org/1969032/avatar/a0f23c893ae54e74.jpg'/> </a> <div><a href="/profile/vikash_8090_b" title="Newbie vikash_8090_b" class="rated-user user-gray">vikash_8090_b</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808890" href="?#comment-808890" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808890" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="1969032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808890"> <div class="moveup"> <div class="ttypography"><p>is there anyone who can't even solve one question of today's contest ..</p></div> </div> </div> <div class="reply info"> <a class="comment-808890 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808890 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808890"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808892" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808892" href="?#comment-808892" style="font-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="808892" 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="808892" class="CommentVoteFrame" data-commentRating="-6" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808892"> <div class="moveup"> <div class="ttypography"><p>Deleted :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808892 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808892 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808892"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808918" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prituladima" style="position: relative;"> <img src='https://userpic.codeforces.org/116750/avatar/ca46d0256a294b26.jpg'/> </a> <div><a href="/profile/prituladima" title="Pupil prituladima" class="rated-user user-green">prituladima</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808918" href="?#comment-808918" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808918" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="116750" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808918"> <div class="moveup"> <div class="ttypography"><p>Please explain div2c/div1a problem a little bit more. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808918 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808918 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808918"> <li> <div class="comment"> <table class="comment-table" commentId="808921" commentParentId="808918"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808921" href="?#comment-808921" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808918" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808921" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808921"> <div class="moveup"> <div class="ttypography"><p>Try out this <a href="https://youtube.com/c/MagentaCobra">channel</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808921 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808921 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808921"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808950" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jakab922" style="position: relative;"> <img src='https://userpic.codeforces.org/53532/avatar/f9515e974f3ebcb1.jpg'/> </a> <div><a href="/profile/jakab922" title="Specialist jakab922" class="rated-user user-cyan">jakab922</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808950" href="?#comment-808950" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808950" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="53532" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808950"> <div class="moveup"> <div class="ttypography"><p>I don't really understand the need for a recursive function for the stack emptying probabilities in <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a>. I mean given that you have a stack of size <code>n</code> and and <code>m</code> you can basically have an array of size <code>n + m</code> filled with <code>0</code>s and <code>1</code>s where <code>0</code> at the <code>i</code>th place means that the <code>i</code>th element was taken from the first stack. Any such array which has <code>n</code> <code>0</code>s and <code>m</code> <code>1</code>s correspond to one process and it's easy to see that whoever takes the last spot in the array gets emptied later which gives an easy way to calculate the probabilities. Namely $$$\binom{n + m - 1}{n - 1} / \binom{n + m}{n}$$$ for the first and similar to the other. </p></div> </div> </div> <div class="reply info"> <a class="comment-808950 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808950 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808950"> <li> <div class="comment"> <table class="comment-table" commentId="808959" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cuom1999" style="position: relative;"> <img src='https://userpic.codeforces.org/253776/avatar/934152bc42a0b10c.jpg'/> </a> <div><a href="/profile/cuom1999" title="Grandmaster cuom1999" class="rated-user user-red">cuom1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808959" href="?#comment-808959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="253776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808959"> <div class="moveup"> <div class="ttypography"><p>If $$$m=2$$$ and $$$n=1$$$, your approach gives $$$\frac{1}{3}$$$. The correct answer should be $$$\frac{1}{4}$$$. </p><p>P/S: I'm also curious if there is any combinatoric approach for this,<a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808959"> <li> <div class="comment"> <table class="comment-table" commentId="809004" commentParentId="808959"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809004" href="?#comment-809004" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809004" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809004"> <div class="moveup"> <div class="ttypography"><p>I would guess that there’s no easy closed form. You can evaluate in $$$O(n)$$$ however by counting right up paths from $$$(a,0)$$$ to $$$(x,y)$$$ for all $$$a$$$ and multiplying by $$$2^{-steps}$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-809004 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809004 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809004"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809366" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/geekpradd" style="position: relative;"> <img src='https://userpic.codeforces.org/367430/avatar/427394aa7f5a63a0.jpg'/> </a> <div><a href="/profile/geekpradd" title="Candidate Master geekpradd" class="rated-user user-violet">geekpradd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809366" href="?#comment-809366" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809366" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="367430" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809366"> <div class="moveup"> <div class="ttypography"><p>The problem with this is that all the possibilities are not equilikely, consider $$$m=2, n=1$$$ and let $$$1$$$ denote entries from the stack of size $$$n$$$. Then the probability of obtaining $$$100$$$ is $$$1/2$$$, while obtaining $$$010$$$ and $$$001$$$ has a probability of $$$1/4$$$. Your approach assumes a uniform prior probability (in which case the answer is indeed $$$1/3$$$ whereas here it is $$$1/4$$$ which is the probability of getting $$$001$$$)</p></div> </div> </div> <div class="reply info"> <a class="comment-809366 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809366 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809366"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thunderboltz" style="position: relative;"> <img src='https://userpic.codeforces.org/1170396/avatar/4f017b259605bc5c.jpg'/> </a> <div><a href="/profile/thunderboltz" title="Newbie thunderboltz" class="rated-user user-gray">thunderboltz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808951" href="?#comment-808951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170396" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808951"> <div class="moveup"> <div class="ttypography"><p>Problem Div2C/Div1A, Plz somebody explain 3rd hint. I didn't get why this condition must be true </p><p><code>The sum of the values of edges with positive weight must be ≥ the maximum value in the array.</code></p></div> </div> </div> <div class="reply info"> <a class="comment-808951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808951"> <li> <div class="comment"> <table class="comment-table" commentId="808995" commentParentId="808951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808995" href="?#comment-808995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808995" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808995"> <div class="moveup"> <div class="ttypography"><p>I like to think about C this way: The cheapest node is the root, and the most expensive node, X, is the one with the highest value, D. Therefore no matter how we make our edges, we need at least 1 path from node to X with distance D. So let's build 1 single edge of positive weight from 1 to X with weight D.</p><p>Now from node X, all other nodes are &lt;= D. We can use negative edges to go there. Now the problem just becomes &quot;assign as many negative edges as possible&quot; to the rest of the nodes. </p></div> </div> </div> <div class="reply info"> <a class="comment-808995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808995"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808971" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808971" href="?#comment-808971" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808971" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808971"> <div class="moveup"> <div class="ttypography"><p>In problem <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a> I agree with everything up to:</p> <blockquote><p>Once l is reached, we now note that the probability that the process &quot;gets closer&quot; to b is always equal to the probability of getting closer to a.</p> </blockquote><p>I agree with this quote if it was about each individual set of marked nodes and single step for them. Because for any individual set of marked nodes, those probabilities is just one over the number of options at the moment. But I don't understand why I should forget about everything else what happens with other parts of tree, because after single step which is neither towards <strong>a</strong> neither towards <strong>b</strong>, the number of options (nodes we can mark on next step) may change.</p></div> </div> </div> <div class="reply info"> <a class="comment-808971 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808971 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808971"> <li> <div class="comment"> <table class="comment-table" commentId="809006" commentParentId="808971"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809006" href="?#comment-809006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808971" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809006" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809006"> <div class="moveup"> <div class="ttypography"><p>That is correct, but to see how it stays the same you can think of it inductively. Use strong induction and assume probability is the same no matter what the state of the tree is. Then from $$$(x,y)$$$ you always have an equal probability of ending up in one of the two states you can transition to because $$$p$$$ is always the same. Every scenario you enter one state, there’s another scenario with the same probability that enters the other state. So, the probability of entering one of the two states is the same as the other, thus $$$0.5$$$. Hopefully that makes things more clear.</p></div> </div> </div> <div class="reply info"> <a class="comment-809006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809006"> <li> <div class="comment"> <table class="comment-table" commentId="809113" commentParentId="809006"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809113" href="?#comment-809113" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809006" style="font-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="809113" 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="809113" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809113"> <div class="moveup"> <div class="ttypography"><p>Oh thanks, it's clear now. So, base of induction is when only <strong>l</strong> reached, and we can show that probability to make step towards <strong>a</strong> and <strong>b</strong> is same because for each individual set you can go from <strong>l</strong> to <strong>b</strong> instead of going from <strong>l</strong> into <strong>a</strong>, using exactly same steps in between (those steps which doesn't change distances to <strong>a</strong> and <strong>b</strong>). And similar holds for next steps.</p></div> </div> </div> <div class="reply info"> <a class="comment-809113 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809113 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809113"> <li> <div class="comment"> <table class="comment-table" commentId="821713" commentParentId="809113"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 08:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821713" href="?#comment-821713" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809113" style="font-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="821713" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="821713" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-821713"> <div class="moveup"> <div class="ttypography"><p>Can you explain this?</p><p>Assume $$$X$$$ is initially node we chose. Then define a function $$$g$$$ :</p><p>$$$g[a][b][STATE]$$$ = probability to reach a before b while state of the tree we reach is $$$STATE$$$, and $$$a$$$, $$$b$$$ is length of path.</p><p><img alt=" " src="/predownloaded/c2/32/c232d053fe3fbd1dedc06e56db58a7c139157987.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>follow the image, I can see : $$$g[a][b][STATE_x] = \frac{1}{4} (g[a][b][STATE_d] + g[a][b][STATE_e] + g[a — 1][b][closer_a] + g[a][b — 1][closer_b])$$$</p><p>It can easy see that the probability can change. Or I wrong in some where?</p></div> </div> </div> <div class="reply info"> <a class="comment-821713 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821713 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821713"> <li> <div class="comment"> <table class="comment-table" commentId="821861" commentParentId="821713"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 18:25">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821861" href="?#comment-821861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821713" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="821861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-821861"> <div class="moveup"> <div class="ttypography"><p>I'll hide my long explanation under spoiler</p> <div class="spoiler"><b class="spoiler-title">horrible wall of text</b><div class="spoiler-content" style="display: none;"><p>To put things into words, I want to define some things. First, suppose we marked some $$$s_1, s_2, s_3 ... s_k$$$ vertices in exact this order. Then, let $$$P(s)$$$ to be probability to mark them in this sequence. It can be decomposed into $$$P(s) = p_1 \cdot p_2 \cdot p_3 \cdot ... \cdot p_k$$$ where $$$p_i = 1/o_{i-1}$$$ where $$$o_i$$$ is number of options at step $$$i$$$ — number of opened vertices, except $$$p_0 = 1/n$$$, or $$$o_0 = n$$$.</p><p>Then, let $$$l = LCA(a, b)$$$ where $$$LCA$$$ is lowest common ancestor. Then, let $$$x_v$$$ to be some sort of 'cost'. For each $$$v$$$ on path between $$$a$$$ and $$$l$$$ it will be distance to $$$l$$$, and $$$-1$$$ everywhere else. Similarly, for each $$$v$$$ on path between $$$b$$$ and $$$l$$$ let $$$y_v$$$ to be distance to $$$l$$$ and $$$-1$$$ everywhere else. Let</p> <center>$$$ A(s) = \max\limits_{v\in s}x_v \\ B(s) = \max\limits_{v\in s}y_v $$$</center><p>Then $$$A(s)$$$ is equal to how far we reach $$$a$$$, and $$$B(s)$$$ is equal to how far we reach $$$b$$$. Let say we are in situation $$$(A(s), B(s))$$$ after marking $$$s$$$, and therefore situation is pair of numbers. Situation $$$(-1,-1)$$$ corresponds that no vertex is marked on path from $$$a$$$ to $$$b$$$. Situation $$$(0,0)$$$ corresponds to only $$$l$$$ marked on path from $$$a$$$ to $$$b$$$. And situation $$$(1,0)$$$ corresponds to $$$l$$$ and single vertex towards $$$a$$$ is marked.</p><p>Finally, let say sequence of marks $$$s$$$ reached state $$$(A(s), B(s))$$$ if either $$$A(s) = x_{s_k}$$$ or $$$B(s) = y_{s_k}$$$, in other words, last vertex is on path from $$$a$$$ to $$$b$$$ and it did change situation.</p><p>Now, what we want to prove is following:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha+1,\beta)} P(s) = \sum\limits_{s\;reached\;(\alpha,\beta+1)} P(s)$$$</center><p><strong>For some fixed</strong> $$$s_1$$$, which is root we chosen. And the way we prove it is that $$$s$$$ that is reached $$$(\alpha+1,\beta)$$$ consists of $$$u$$$ that reached $$$(\alpha,\beta)$$$ plus additional steps: $$$w$$$ plus $$$s_k$$$. So $$$s = u..w..s_k$$$ where $$$..$$$ is concatenation. It's easy to see what none of vertices from $$$w$$$ is on path from $$$a$$$ to $$$b$$$. Also, it's easy to see that we could instead of choosing $$$s_k$$$ could choose vertex $$$z$$$ towards $$$b$$$, and it would have same probability. In other words $$$P(s) = P(u..w..z)$$$. And this $$$u..w..z$$$ should reach state $$$(\alpha, \beta+1)$$$. So it should be in right side sum of our equation we want to prove.</p><p>So, for any $$$s$$$ from left sum, we can make $$$s'$$$ from right sum in unique way, and it will have same $$$P(s) = P(s')$$$. Similarly, for any $$$s$$$ from right sum, we can make $$$s'$$$ from left sum in unique way, and it will have same $$$P(s) = P(s')$$$. So this is bijection, and each element from left sum corresponds to element from right sum with same value, so those sums should have same value. Therefore it's equality.</p><p>Initially I wanted to trim $$$s$$$ from $$$(\alpha+1,\beta)$$$ to $$$(\alpha,\beta)$$$ and show similar thing based on following sum:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha,\beta)} P(s)$$$</center><p>Which is probability to reach state $$$(\alpha, \beta)$$$, but luckily it didn't required. I'll use notation $$$P(reach(\alpha, \beta))$$$ for this probability.</p><p>Thing that is not covered though: why this equality can be translated into probability $$$= 1/2$$$? Well, from $$$(\alpha, \beta)$$$ you eventually will reach either $$$(\alpha+1,\beta)$$$ or $$$(\alpha,\beta+1)$$$, so you can see this as example of Law of total probability. $$$P(reach(\alpha, \beta)) = P(reach (\alpha+1, \beta)) + P(reach (\alpha, \beta+1))$$$, because events $$$(\alpha+1,\beta)$$$ and $$$(\alpha,\beta+1)$$$ are disjoint events given $$$(\alpha, \beta)$$$ is reached. And we proved they have equal probability so $$$P(reach(\alpha, \beta)) = 2\cdot P(reach (\alpha+1, \beta))$$$, so $$$P(reach (\alpha+1, \beta)) = 1/2\cdot P(reach(\alpha, \beta))$$$ which we actually use.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-821861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821861"> <li> <div class="comment"> <table class="comment-table" commentId="822027" commentParentId="821861"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/28/2021 13:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822027" href="?#comment-822027" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821861" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="822027" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822027"> <div class="moveup"> <div class="ttypography"><p>Oh, sorry, there is one missing part. We proved $$$P(reached(\alpha+1,\beta))=P(reached(\alpha,\beta+1))$$$ <strong>given</strong> $$$(\alpha,\beta)$$$ is reached, but this is actually what we need. This <strong>given</strong> condition is what I missed. Without <strong>given</strong> we could reach $$$(\alpha+1,\beta)$$$ from reaching $$$(\alpha+1,\beta-1)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-822027 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822027 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822027"> <li> <div class="comment"> <table class="comment-table" commentId="822370" commentParentId="822027"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 13:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822370" href="?#comment-822370" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822027" style="font-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="822370" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="822370" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822370"> <div class="moveup"> <div class="ttypography"><p>Thanks for amz explain. I realize that I had some missunderstand in the way we calc $$$P(reach\ A\ before\ B)$$$</p><p>This's exactly what in my mind one day ago: let $$$s = ...a...b...$$$ where $$$a$$$ and $$$b$$$ is node $$$a$$$ and node $$$b$$$, &quot;$$$...$$$&quot; mean some node between them which we chose them in exactly that order, or in other word, $$$s$$$ is state represent what we chose (exact in this order) I think $$$P(reach\ A\ before\ B)$$$ (or $$$P(A&lt;B)$$$) must be calculate in this way :</p><p>$$$P(A&lt;B) = \sum_{\substack{all\ s\ which\ a&lt;b}} P(s)$$$</p><p>But unfortunately, it's wrong (may be, or I still missunderstanding)</p><p>$$$P(A) = \sum_{\substack{all\ B[i]\ \subseteq\ A}} P(B[i])$$$ if and only if all $$$B[i]$$$ are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-822370 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822370 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822370"> <li> <div class="comment"> <table class="comment-table" commentId="822755" commentParentId="822370"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 22:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822755" href="?#comment-822755" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822370" style="font-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="822755" 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="822755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822755"> <div class="moveup"> <div class="ttypography"><p>$$$P(A &lt; B)$$$ in your terms is exactly what we need (if a = A and b = B).</p><p>I don't understand last formula, everything else looks fine.</p><p>And to find $$$P(A &lt; B)$$$ we use fact above and calculate all possible ways to reach $$$a$$$ earlier than $$$b$$$ we use $$$(\alpha, \beta)$$$ states using my notation: you either get $$$\alpha$$$ equal to dist to $$$a$$$ when $$$\beta$$$ = 0, or $$$\beta$$$ = 1, or 2, or 3...</p> <center>$$$ P(A &lt; B) = \\ =\sum\limits_{i=0}^{dist(b,l)}P(reach(dist(a,l),i)\;given\; reached(dist(a,l)-1,i)) \\ = \sum\limits_{i=0}^{dist(b,l)}P(reached(dist(a,l)-1,i))\cdot \frac{1}{2} $$$</center><p>Or you can rephrase task into other task with two kind of balls. What probability to remove all balls of one kind earlier than other, if you pick one or other kind of ball with probability 1/2.</p></div> </div> </div> <div class="reply info"> <a class="comment-822755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822755"> </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="808983" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/xsc" style="position: relative;"> <img src='https://userpic.codeforces.org/343/avatar/9eaf243b1eb8c3d4.jpg'/> </a> <div><a href="/profile/xsc" title="Specialist xsc" class="rated-user user-cyan">xsc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808983" href="?#comment-808983" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808983" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="343" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808983"> <div class="moveup"> <div class="ttypography"><p>Div2 D, O(N^4) solution <a href="/contest/1541/submission/120623566" title="Посылка 120623566 от xsc">120623566</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808983 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808983 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808983"> <li> <div class="comment"> <table class="comment-table" commentId="809278" commentParentId="808983"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DavidXu_JJ" style="position: relative;"> <img src='https://userpic.codeforces.org/2003708/avatar/623dc8036b4e9d72.jpg'/> </a> <div><a href="/profile/DavidXu_JJ" title="Expert DavidXu_JJ" class="rated-user user-blue">DavidXu_JJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809278" href="?#comment-809278" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808983" style="font-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="809278" 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="809278" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2003708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809278"> <div class="moveup"> <div class="ttypography"><p>Your code really helps me a lot in debugging,thanks.</p><p>By the way,it's weired that I get Wrong6 when I try to optimize to O(N^3*logN) by binary search on tree.</p><p>I have tested my function on other online judge and my function seems to be correct.</p></div> </div> </div> <div class="reply info"> <a class="comment-809278 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809278 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809278"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809018" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ducati" style="position: relative;"> <img src='https://userpic.codeforces.org/699102/avatar/eff3c352646e914e.jpg'/> </a> <div><a href="/profile/ducati" title="Grandmaster ducati" class="rated-user user-red">ducati</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 03:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809018" href="?#comment-809018" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809018" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="699102" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809018"> <div class="moveup"> <div class="ttypography"><p>Although Div.2 D is harder than ever, in my opinion, it's such a useful and excellent problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-809018 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809018 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809018"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809046" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KanishkGoel" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/KanishkGoel" title="Expert KanishkGoel" class="rated-user user-blue">KanishkGoel</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809046" href="?#comment-809046" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809046" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1917239" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809046"> <div class="moveup"> <div class="ttypography"><p>Is it usual for people to post solutions online during the contest like this channel? <a href="https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ">https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809046 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809046 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809046"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809051" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809051" href="?#comment-809051" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809051"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain why this submission <a href="/contest/1541/submission/120562335" title="Посылка 120562335 от Karnania7201">120562335</a> is failing for Div2 B? It would be a great help.</p></div> </div> </div> <div class="reply info"> <a class="comment-809051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809051"> <li> <div class="comment"> <table class="comment-table" commentId="809076" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809076" href="?#comment-809076" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809076" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809076"> <div class="moveup"> <div class="ttypography"><p>Bro you did not included the condition that i and j should be different i.e (i != j) because it is given in question that no are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-809076 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809076 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809076"> <li> <div class="comment"> <table class="comment-table" commentId="809079" commentParentId="809076"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:08">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809079" href="?#comment-809079" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809076" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809079" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809079"> <div class="moveup"> <div class="ttypography"><p>I think its covered as I started j from i+1. I tried that explicitly too but it didn't work. I wrote the same idea in a different way and it worked but this kind of implementation is not working.</p></div> </div> </div> <div class="reply info"> <a class="comment-809079 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809079 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809079"> <li> <div class="comment"> <table class="comment-table" commentId="809082" commentParentId="809079"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809082" href="?#comment-809082" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809079" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809082" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809082"> <div class="moveup"> <div class="ttypography"><p>yeah, you are right, I run your code using vector instead of creating memeset it worked fine, i guess there is some problem in that. <a href="https://codeforces.com/contest/1541/submission/120633207">120633207</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809082 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809082 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809082"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809081" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_NICkk" style="position: relative;"> <img src='https://userpic.codeforces.org/1543175/avatar/6084dd87f2c1cad9.jpg'/> </a> <div><a href="/profile/_NICkk" title="Expert _NICkk" class="rated-user user-blue">_NICkk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809081" href="?#comment-809081" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809081" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1543175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809081"> <div class="moveup"> <div class="ttypography"><p>Only fault in your code is that you didn't used memset correctly </p><p>I just changed your memset with this &quot; memset(ind, 0, sizeof(ind)) &quot; and it worked perfectly fine</p></div> </div> </div> <div class="reply info"> <a class="comment-809081 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809081 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809081"> <li> <div class="comment"> <table class="comment-table" commentId="809091" commentParentId="809081"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:37">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809091" href="?#comment-809091" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809081" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809091" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809091"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot to both of you. I shouldn't have used it without properly knowing about it. </p></div> </div> </div> <div class="reply info"> <a class="comment-809091 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809091 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809091"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809064" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vrintle" style="position: relative;"> <img src='https://userpic.codeforces.org/1991777/avatar/24d9007095afbbb6.jpg'/> </a> <div><a href="/profile/vrintle" title="Master vrintle" class="rated-user user-orange">vrintle</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809064" href="?#comment-809064" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809064" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1991777" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809064"> <div class="moveup"> <div class="ttypography"><p>Instead of $$$a_i \cdot a_j \leq 2n$$$, we could also check $$$a_i \cdot a_j \leq i+n$$$ which is a bit faster ($$$ \sim 62ms$$$).</p></div> </div> </div> <div class="reply info"> <a class="comment-809064 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809064 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809064"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809066" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809066" href="?#comment-809066" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809066" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809066"> <div class="moveup"> <div class="ttypography"><p>can anyone explain B. pleasant pairs more easy words?? </p></div> </div> </div> <div class="reply info"> <a class="comment-809066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809066"> <li> <div class="comment"> <table class="comment-table" commentId="809067" commentParentId="809066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809067" href="?#comment-809067" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809067" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809067"> <div class="moveup"> <div class="ttypography"><p>And also what is ask in 3rd question i cant understand what asked in it</p></div> </div> </div> <div class="reply info"> <a class="comment-809067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809067"> <li> <div class="comment"> <table class="comment-table" commentId="809070" commentParentId="809067"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809070" href="?#comment-809070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809067" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809070"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">https://www.youtube.com/watch?v=xCj_ZR5kENo</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809098" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809098" href="?#comment-809098" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809098" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809098"> <div class="moveup"> <div class="ttypography"><p>For those who are searching for a simple solution for great Graphs problems in O (nlogn). <a href="https://codeforces.com/contest/1541/submission/120600816">https://codeforces.com/contest/1541/submission/120600816</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809098 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809098 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809098"> <li> <div class="comment"> <table class="comment-table" commentId="809119" commentParentId="809098"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fjvzr" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/fjvzr" title="Newbie fjvzr" class="rated-user user-gray">fjvzr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809119" href="?#comment-809119" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809098" style="font-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="809119" 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="809119" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1623986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809119"> <div class="moveup"> <div class="ttypography"><p>Bro can u explain this soln????? i thought of taking all pairs that give negative edges except for the adjacent pairs.... bt getting wrong ans in 3rd 4th test case.....</p><p>while(n&gt;2) { sum-=(n-2)*(llabs(a[j]-a[i])); n--; // n = size i++; // i = 0 j--; // j = n-1 } cout&lt;&lt;sum&lt;&lt;endl;</p><p><a href="https://codeforces.com/contest/1541/submission/120636509">mysoln</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809119 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809119 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809119"> <li> <div class="comment"> <table class="comment-table" commentId="809124" commentParentId="809119"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809124" href="?#comment-809124" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809119" style="font-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="809124" 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="809124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809124"> <div class="moveup"> <div class="ttypography"><p>My solution is simple. First sort the array. </p><p>Then start connecting adjacent values with their differences. This way sum of all edges with positive weight will be same as the sum of adjacent differences in the array.</p><p>After that start making negative edges for every i. So each i will have i negative edges. Where negative weight is same as -(arr[i] — arr[j]).</p><p>Instead of search it for every j I have formula as (prefixsum till i) — arr[i]*i</p></div> </div> </div> <div class="reply info"> <a class="comment-809124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809124"> <li> <div class="comment"> <table class="comment-table" commentId="809132" commentParentId="809124"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809132" href="?#comment-809132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809124" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809132"> <div class="moveup"> <div class="ttypography"><p>can you tell me why are we sorting the array for a particular node call it x we need to add a negative weight from x to 1 , x to 2 x to 3 till x to x-1 keeping in mind the the path sum doesn't become negative so why are we sorting the array</p></div> </div> </div> <div class="reply info"> <a class="comment-809132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809132"> <li> <div class="comment"> <table class="comment-table" commentId="809135" commentParentId="809132"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809135" href="?#comment-809135" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809135" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809135"> <div class="moveup"> <div class="ttypography"><p>We are sorting values only once so as to connect neighboring nodes with minimum values,i.e. difference b/w consecutive values.<br /> From this sum of positive edges will be minimum.</p></div> </div> </div> <div class="reply info"> <a class="comment-809135 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809135 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809135"> <li> <div class="comment"> <table class="comment-table" commentId="809139" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809139" href="?#comment-809139" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809139" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809139"> <div class="moveup"> <div class="ttypography"><p>ohhh thanks I got it</p></div> </div> </div> <div class="reply info"> <a class="comment-809139 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809139 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809139"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809145" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809145" href="?#comment-809145" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809145" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809145"> <div class="moveup"> <div class="ttypography"><p>My solution is working now I only needed to sort the array my code would have been accepted during the contest :(</p></div> </div> </div> <div class="reply info"> <a class="comment-809145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809145"> </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="809116" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ken_KaNeKi_997" style="position: relative;"> <img src='https://userpic.codeforces.org/1737228/avatar/50ceb845253df5d4.jpg'/> </a> <div><a href="/profile/Ken_KaNeKi_997" title="Newbie Ken_KaNeKi_997" class="rated-user user-gray">Ken_KaNeKi_997</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809116" href="?#comment-809116" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809116" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1737228" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809116"> <div class="moveup"> <div class="ttypography"><p>can anyone explain div2 B plz</p></div> </div> </div> <div class="reply info"> <a class="comment-809116 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809116 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809116"> <li> <div class="comment"> <table class="comment-table" commentId="809204" commentParentId="809116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809204" href="?#comment-809204" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809116" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809204" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809204"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/92199#comment-809178">here</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809204 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809204 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809204"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809122" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809122" href="?#comment-809122" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809122" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809122"> <div class="moveup"> <div class="ttypography"><p>Beautiful Problems. Amazing Round!!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-809122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809122"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809156" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dummybawa" style="position: relative;"> <img src='https://userpic.codeforces.org/1704408/avatar/1522f670cd21321.jpg'/> </a> <div><a href="/profile/dummybawa" title="Expert dummybawa" class="rated-user user-blue">dummybawa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809156" href="?#comment-809156" style="font-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="809156" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809156" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1704408" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809156"> <div class="moveup"> <div class="ttypography"><p>UPD: It's wrong. </p></div> </div> </div> <div class="reply info"> <a class="comment-809156 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809156 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809156"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809178" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809178" href="?#comment-809178" style="font-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="809178" 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="809178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809178"> <div class="moveup"> <div class="ttypography"><p>For DIV 2C/1A can anyone explain with this test case N = 6 and D = 0 1 2 3 2 3. What are the edges that we can have with their weights?</p></div> </div> </div> <div class="reply info"> <a class="comment-809178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809178"> <li> <div class="comment"> <table class="comment-table" commentId="809198" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Zemrith" style="position: relative;"> <img src='https://userpic.codeforces.org/1159882/avatar/2a6566e372882267.jpg'/> </a> <div><a href="/profile/Zemrith" title="Expert Zemrith" class="rated-user user-blue">Zemrith</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809198" href="?#comment-809198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-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="809198" 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="809198" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159882" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809198"> <div class="moveup"> <div class="ttypography"><p>Hello! The answer would be -18.</p><p>Diagram: <img alt=" " src="/predownloaded/8c/88/8c88a0230dea9f499896ee59def659611c605976.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Notice that once you sort the distances, the adjacent nodes have no effect on your final answer. But you can add negative edges as long as they are not adjacent, resulting in such a diagram. Hence you can use prefix sums to solve the problem. (if x nodes came before this, for each node, the answer to add is (x-1)*curr value — csum of first (x-1) nodes). </p><p>Hope that made sense!</p></div> </div> </div> <div class="reply info"> <a class="comment-809198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809198"> <li> <div class="comment"> <table class="comment-table" commentId="809218" commentParentId="809198"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:27">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809218" href="?#comment-809218" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809218" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809218"> <div class="moveup"> <div class="ttypography"><p>Thank you <a class="rated-user user-cyan" href="/profile/Zemrith" title="Специалист Zemrith">Zemrith</a> for so much detail explanation and the solution too it helped me a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-809218 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809218 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809218"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809199" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809199" href="?#comment-809199" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809199" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809199"> <div class="moveup"> <div class="ttypography"><p>first sort the array they will from non negative weight edges. 0 -&gt; 1 -&gt; 2 -&gt; 2 -&gt; 3 -&gt; 3 so the non negative weights will be 1 | 1 | 0 | 1 | 0. form here greedily build most negative weights(backward edges) such that there are no negative cycles.</p></div> </div> </div> <div class="reply info"> <a class="comment-809199 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809199 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809199"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809203" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809203" href="?#comment-809203" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809203" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809203"> <div class="moveup"> <div class="ttypography"><p>First you can sort D and get: <code> N = 6, D = [0, 1, 2, 2, 3, 3] </code></p><p>Now calculate the diffs:</p><p><code>diffs = [1, 1, 0, 1, 0]</code></p><p>The edges for this graph could be something like this:</p> <pre><code> 1 1 0 1 0 &lt;- forward edges 1 &lt;-&gt; 2 &lt;-&gt; 3 &lt;-&gt; 4 &lt;-&gt; 5 &lt;-&gt; 6 -1 -1 0 -1 0 &lt;- backward edges </code></pre><p>Now you have to add more negatives edges, and you could do this by choosing some <code>i</code> and <code>j</code>, <code>i &lt; j</code> and add an edges from <code>j</code> to <code>i</code>, and the weight will be sum of the values from <code>diff[i]</code> to <code>diff[j]</code>.</p><p>Another way to think about this is: look at <code>D</code> array, it represents distances between adjacent nodes, all we have to do is add all of the edges with length 2, then all of the edges of length 3, ..., all of the edges of length <code>N - 1</code>.</p><p>So, for our case we would have these edges</p> <pre><code>a b W ------- 1 2 - 1 2 3 - 1 3 4 - 0 &lt;- adjacent forward edges 4 5 - 1 5 6 - 0 2 1 - -1 3 2 - -1 4 3 - 0 &lt;- adjacent backward edges 5 4 - -1 6 5 - 0 3 1 - -2 4 2 - -1 5 3 - -1 &lt;- edges of length 2 6 4 - -1 4 1 - -2 5 2 - -2 &lt;- edges of length 3 6 3 - -1 5 1 - -3 6 2 - -2 &lt;- edges of length 4 6 1 - -3 &lt;- edges of length 5 </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809203 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809203 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809203"> <li> <div class="comment"> <table class="comment-table" commentId="809221" commentParentId="809203"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809221" href="?#comment-809221" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809203" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809221" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809221"> <div class="moveup"> <div class="ttypography"><p>Thank You <a class="rated-user user-green" href="/profile/ilidar" title="Ученик ilidar">ilidar</a> for clearing my doubt and for detailed explaination.</p></div> </div> </div> <div class="reply info"> <a class="comment-809221 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809221 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809221"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809280" href="?#comment-809280" style="font-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="809280" revisionCount="7" revision="7"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">7</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809280" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+18</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809280"> <div class="moveup"> <div class="ttypography"><p>Could someone please provide a more strict intuition or insight of Div2D/Div1B of why &quot;the actual probability p does not matter&quot;? The intuition in the editorial is still alien to me of why those choices of not progess toward to either stacks (and probability 'p' also changes from time to time too) doesn't matter.</p><p>Update: Here is the intuition I came up with (The strict proof can be found in the comment of the author below)</p><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left) in some states of the current tree.</p><p>now, we will try break this $$$dp_{i,j}$$$ down into the sum of $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$</p><p>We will try to illustrate this with trying to split and color, either red or blue, a stick of length $$$1$$$. The length of the sticks representing the 'probability', and the color of the sticks will represent $$$dp_{i-1,j}$$$(red) or $$$dp_{i,j-1}$$$(blue), depending on the color.</p><p>Suppose in the current state, we have probability $$$p$$$ for choosing to pop each stacks, and the rest $$$1-2p$$$ of doing nothing. The picture will look like this:</p><p><a href="https://ibb.co/q9HjQTm"><img alt="Tree-Array-Rep" border="0" src="/predownloaded/13/57/135732d2b0967af0f76c1dba28df72086f234c7d.png" style="max-width: 100.0%;max-height: 100.0%;" /></a></p><p>We will split the stick equally(*) into several sticks of length $$$p$$$, and then color two of them red and blue. (* We can split it evenly because in the original problem, $$$p$$$ is in the form $$$\frac{1}{number\ of\ candidate\ unmark\ nodes}$$$ ) Now, the remaining sticks represent the state of $$$dp_{i,j}$$$ again (in some other state of the entire tree, so might be in some different $$$p$$$). That means we will split those sticks similary.</p><p>The key observations is:</p><p>1) We know that, in the original problem, if we keep picking nodes that aren't progressing toward the target nodes, we will run out of nodes eventually and finally choose the two nodes. That means, all the sticks will eventually colored into 'red' and 'blue'.</p><p>2) When we split a stick into several smaller equal length sticks, we will color two of them into red and blue. <strong>Those two sticks always have the same length</strong>. That means, the total length of blue sticks and the total length of red sticks will be equal in the end.</p><p>Analogically, that means, eventually, $$$dp_{i,j}$$$ will split into $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$ evenly, no matter $$$p$$$ might be or the state of tree of $$$dp_{i,j}$$$ might be. Therefore, $$$dp_{i,j} = \frac{1}{2} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-809280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809280"> <li> <div class="comment"> <table class="comment-table" commentId="809284" commentParentId="809280"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809284" href="?#comment-809284" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809280" style="font-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="809284" 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="809284" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809284"> <div class="moveup"> <div class="ttypography"><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left), with having arbitary probability $$$0 &lt; p \leq 0.5$$$ of chosing to pick the top of each stack (and $$$1-2p$$$ for doing nothing). Then</p><p>$$$dp_{i,j}=\int_{0}^{0.5} x \cdot (dp_{i-1,j}+dp_{i,j-1}) + (1-2x) \cdot dp_{i,j} \,dx$$$</p><p>Solving the equation, we get $$$dp_{i,j}=\frac{1}{6} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$ What is the mistake in this logic?</p></div> </div> </div> <div class="reply info"> <a class="comment-809284 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809284 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809284"> <li> <div class="comment"> <table class="comment-table" commentId="809399" commentParentId="809284"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809399" href="?#comment-809399" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809284" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809399" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809399"> <div class="moveup"> <div class="ttypography"><p>The biggest issue with this logic is that it's assuming $$$p$$$ is arbitrary chosen from a certain state. While $$$p$$$ can be anything in the world, it is always an exact number from a certain state, hence why an integral is wrong. </p><p>As a different type of intuition, you can think, &quot;is it more likely to reach $$$(i-1, j)$$$ than state $$$(i, j-1)$$$&quot;? and vice versa. For me at least, I don't see how it's possible for either of those questions to be true, so they should be equal.</p><p>If you're looking for a more rigorously correct $$$dp$$$, it would look something like this.</p> <div class="spoiler"><b class="spoiler-title">Proof</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp_{i, j, S}$$$ denote the probability of reaching some node $$$i$$$ distance away before some node $$$j$$$ distance away where $$$S$$$ is a representation of the entire state of of the process (not necessarily an integer). I think you already understood why we can assume the $$$lca$$$ is already reached. We aim to show that $$$S$$$ does not matter in our calculation. Assume inductively that $$$S$$$ does not matter. So, we can assume that states $$$(i-1, j)$$$ and states $$$(i, j-1)$$$ are irrelevant to $$$S$$$. Hence, the part we need to care about is $$$(1-2p) dp_{i, j, S \rightarrow S_a}$$$. A way of thinking about this part of the transition is moving through the collection of $$$S$$$ with the state $$$(i, j)$$$. Obviously, the $$$dp$$$ is a $$$DAG$$$ because no state $$$S$$$ can reach another. Each bounce takes a certain probability $$$p$$$ which is just multiplied in the current path. So, for each state $$$S$$$ with state $$$(i, j)$$$, we have a certain probability to reach it by simply calculating $$$dp$$$ along a DAG as is traditional. Then, from those states of $$$(i, j)$$$ you transition to $$$(i, j-1)$$$ with an equal probability $$$(i-1, j)$$$. So, they have to be equal. Finally, this argument holds for any initial state $$$S$$$ that you reach, so we can conclude that, from any state $$$S$$$ with a state of $$$(i, j)$$$, the probability of transitions to $$$(i-1, j)$$$ and $$$(i, j-1)$$$ are always exactly $$$0.5$$$.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-809399 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809399 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809399"> <li> <div class="comment"> <table class="comment-table" commentId="809701" commentParentId="809399"> <tr> <td class="left"> <div style="position: absolute; left: 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/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809701" href="?#comment-809701" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809399" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809701" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809701"> <div class="moveup"> <div class="ttypography"><p>I see, thank you so much!</p></div> </div> </div> <div class="reply info"> <a class="comment-809701 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809701 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809701"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809298" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/satyam_singh93" style="position: relative;"> <img src='https://userpic.codeforces.org/1763011/avatar/9d9fa405de19ab0e.jpg'/> </a> <div><a href="/profile/satyam_singh93" title="Newbie satyam_singh93" class="rated-user user-gray">satyam_singh93</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809298" href="?#comment-809298" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809298" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1763011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809298"> <div class="moveup"> <div class="ttypography"><p>I am getting wrong ans . could someone tell me where the code make differene ( [yestrday competiton problem .</p><p>`](<a href="https://codeforces.com/contest/1541/problem/B)">https://codeforces.com/contest/1541/problem/B)</a>.</p> <pre><code>int main( ) { clock_t begin = clock(); file_i_o(); // Write your code here.... int t; cin&gt;&gt;t; while(t-- ){ int n; cin&gt;&gt;n; vector&lt;pair&lt;int,int&gt;&gt;v; v.push_back({0,0}); loop(i,0,n) { int x; cin&gt;&gt;x; v.pb({x,i+1}); } sort(v.begin()+1,v.end()); int count =0; for(int i=1 ; i&lt;=n;i++) { for(ll j=i+1;j&lt;=n;j++) { ll left = v[i].first * v[j].first; ll right = v[i].second + v[j].second; if(left == right) count++; if(left &gt; 2*n ) break; } } cout&lt;&lt;count&lt;&lt;endl; } </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809298 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809298 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809298"> <li> <div class="comment"> <table class="comment-table" commentId="809305" commentParentId="809298"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809305" href="?#comment-809305" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809298" style="font-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="809305" 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="809305" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809305"> <div class="moveup"> <div class="ttypography"><p>v[i].first * v[j].first can create overflow. So, you need to convert them to long long by using</p><p>ll left = 1LL * v[i].first * v[j].first;</p><p>instead and it would pass.</p><p>(Simply save the value in long long won't help. You need to convert them to long long before doing multiplication. 1LL* is one way)</p></div> </div> </div> <div class="reply info"> <a class="comment-809305 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809305 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809305"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809309" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809309" href="?#comment-809309" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809309" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809309"> <div class="moveup"> <div class="ttypography"><p>Hi, in problem Div1.B/Div2.D; I can't wrap my head around $$$F[x][y]=F[x−1][y]/2+F[x][y−1]/2$$$. Why is it not $$$F[x][y]=F[x−1][y+1]/2+F[x+1][y−1]/2$$$, can someone please explain to me why is my transition wrong and/or why is the aforementioned transition correct? </p></div> </div> </div> <div class="reply info"> <a class="comment-809309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809309"> <li> <div class="comment"> <table class="comment-table" commentId="809311" commentParentId="809309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809311" href="?#comment-809311" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809311" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809311"> <div class="moveup"> <div class="ttypography"><p>x and y is the distance left for each side right? So, if you take one out, it won't make sense to add that one to the other side since the distance should be either x-1 and y or x and y-1.</p></div> </div> </div> <div class="reply info"> <a class="comment-809311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809311"> <li> <div class="comment"> <table class="comment-table" commentId="809339" commentParentId="809311"> <tr> <td class="left"> <div style="position: absolute; left: 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/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809339" href="?#comment-809339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809339" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809339"> <div class="moveup"> <div class="ttypography"><p>Thank you so much I understand. I had a minor misunderstanding of the parameters to the dp state.</p></div> </div> </div> <div class="reply info"> <a class="comment-809339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809339"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809371" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:13">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809371" href="?#comment-809371" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809371" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809371"> <div class="moveup"> <div class="ttypography"><p>PLease explain why 2 same codes are not giving the same ans</p><p>code forces round 728 div2<br />Problem B :<a href="https://codeforces.com/contest/1541/problem/B">https://codeforces.com/contest/1541/problem/B</a></p><p>AC Submission : <a href="https://ide.codingblocks.com/s/579769">https://ide.codingblocks.com/s/579769</a></p><p>Wrong output Submission :<a href="https://ide.codingblocks.com/s/579771">https://ide.codingblocks.com/s/579771</a></p><p>Difference is using of macro (node) instead of pair&lt;int,int&gt; </p><p>Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-809371 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809371 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809371"> <li> <div class="comment"> <table class="comment-table" commentId="809379" commentParentId="809371"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809379" href="?#comment-809379" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809371" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809379" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809379"> <div class="moveup"> <div class="ttypography"><p>If i am using #define node pair&lt;int,int&gt; it is getting accepted but when i am using typedef pair&lt;int,int&gt; node; it is giving wrong answer</p><p>Why this is happening ?? Is it a bug??</p></div> </div> </div> <div class="reply info"> <a class="comment-809379 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809379 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809379"> <li> <div class="comment"> <table class="comment-table" commentId="809407" commentParentId="809379"> <tr> <td class="left"> <div style="position: absolute; left: 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/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 19:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809407" href="?#comment-809407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809379" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809407" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809407"> <div class="moveup"> <div class="ttypography"><p>Not really sure why this is happening.</p><p>However, I think the problem is the position of #define int long long. So, for #define pair&lt;int,int&gt; node it seems that compiler change node -&gt; pair&lt;int,int&gt; -&gt; pair&lt;long long, long long&gt;. However, when you do typedef, it still keeps in pair&lt;int, int&gt; which creates an overflow problem later on. </p><p>I did try moving #define int long long up above typedef and the code pass. So, my best guess is #define int long long only replace int after that position with long long. Thus, node is still pair&lt;int, int&gt; in the typedef solution, while node is changed to pair&lt;long long, long long&gt; in the second solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-809407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809407"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809627" href="?#comment-809627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809627"> <div class="moveup"> <div class="ttypography"><p>May I ask why in the Div1D solution ci=i-bi, I think it should be ci=bi ...</p></div> </div> </div> <div class="reply info"> <a class="comment-809627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809627"> <li> <div class="comment"> <table class="comment-table" commentId="809631" commentParentId="809627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809631" href="?#comment-809631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809631" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809631"> <div class="moveup"> <div class="ttypography"><p>Check the definition of bi again dude. bi here means <strong>number of elements greater than pi</strong>. So to get ci, which is <strong>number of elements smaller than pi</strong>, you need i-bi.</p></div> </div> </div> <div class="reply info"> <a class="comment-809631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809631"> <li> <div class="comment"> <table class="comment-table" commentId="809636" commentParentId="809631"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809636" href="?#comment-809636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809636"> <div class="moveup"> <div class="ttypography"><p>I read it again. If I read it correctly, bi stands for j&lt;i,pj&gt;pi, and ci stands for j&gt;i,pj&lt;pi. For example, p={1,3,5,4,6,2}, I think b4=1,c4=1, please point out my problem</p></div> </div> </div> <div class="reply info"> <a class="comment-809636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809636"> <li> <div class="comment"> <table class="comment-table" commentId="809638" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809638" href="?#comment-809638" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809638" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809638"> <div class="moveup"> <div class="ttypography"><p>oh, the array index starts from 1</p></div> </div> </div> <div class="reply info"> <a class="comment-809638 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809638 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809638"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809639" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809639" href="?#comment-809639" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809639" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809639"> <div class="moveup"> <div class="ttypography"><p>You are right.</p><p>I guess it might just be typo and ci stands for j&lt;i, pj&lt;pi. At least with this definition of ci the algorithm seems correct :)</p></div> </div> </div> <div class="reply info"> <a class="comment-809639 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809639 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809639"> <li> <div class="comment"> <table class="comment-table" commentId="809641" commentParentId="809639"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809641" href="?#comment-809641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809639" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809641"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-809641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809641"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809705" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/darthrevenge" style="position: relative;"> <img src='https://userpic.codeforces.org/1567000/avatar/ee31d2a91a9575b9.jpg'/> </a> <div><a href="/profile/darthrevenge" title="Candidate Master darthrevenge" class="rated-user user-violet">darthrevenge</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809705" href="?#comment-809705" style="font-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="809705" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809705" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1567000" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809705"> <div class="moveup"> <div class="ttypography"><p>Here's my solution of B div 1 / D div 2 without LCA, using single DFS per node. <a href="/contest/1540/submission/120700765" title="Посылка 120700765 от darthrevenge">120700765</a> It is similar to what <a class="rated-user user-violet" href="/profile/OleschY" title="Кандидат в мастера OleschY">OleschY</a> suggested above. I've tried to describe it in the <a href="https://codeforces.com/blog/entry/92284">blog</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-809705 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809705 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809705"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809951" href="?#comment-809951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809951"> <div class="moveup"> <div class="ttypography"><p>Can someone explain how you can find the LCA for each pair so quick? Iterating through every root is and then considering every pair is already N^3</p></div> </div> </div> <div class="reply info"> <a class="comment-809951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809951"> <li> <div class="comment"> <table class="comment-table" commentId="809965" commentParentId="809951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PurpleCrayon" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809965" href="?#comment-809965" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809965" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="1604355" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809965"> <div class="moveup"> <div class="ttypography"><p>There are a couple ways you could do it:</p> <ol> <li>Just use standard binary lifting (initialize once for each root). This runs in $$$\mathcal{O}(n^3 \log{}n)$$$, and should pass under the given constraints. You could also just use $$$\mathcal{O}(1)$$$ lca using an rmq over an euler tour.</li> <li>You could use a version of dp, where $$$dp[a][b] = lca(a, b)$$$. If the depth of $$$a$$$ is greater than the depth of $$$b$$$, $$$dp[a][b] = dp[parent[a]][b]$$$, otherwise $$$dp[a][b] = dp[a][parent[b]]$$$. The base cases are $$$dp[a][a] = a$$$ for all $$$a$$$. This runs in $$$\mathcal{O}(n^3)$$$.</li> <li>You could extend this idea and do the main solution's dp directly on the tree (without ever worrying about lca's). The recurrence is equivalent to the main solution ($$$dp[a][b] = \frac{dp[parent[a]][b]+dp[a][parent[b]]}{2}$$$ with the base cases being one node is an ancestor of the other.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-809965 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809965 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809965"> <li> <div class="comment"> <table class="comment-table" commentId="809967" commentParentId="809965"> <tr> <td class="left"> <div style="position: absolute; left: 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/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809967" href="?#comment-809967" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809965" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809967" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809967"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the detailed answer!</p></div> </div> </div> <div class="reply info"> <a class="comment-809967 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809967 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809967"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="810320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Anurag_20" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Anurag_20" title="Specialist Anurag_20" class="rated-user user-cyan">Anurag_20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/30/2021 19:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810320" href="?#comment-810320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810320" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1600346" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810320"> <div class="moveup"> <div class="ttypography"><p>O(n2) is also working for div2 C Great Graphs. <a href="https://codeforces.com/contest/1540/submission/120964787">https://codeforces.com/contest/1540/submission/120964787</a></p></div> </div> </div> <div class="reply info"> <a class="comment-810320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810320"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="813828" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/T404" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/T404" title="Master T404" class="rated-user user-orange">T404</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/09/2021 19:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-813828" href="?#comment-813828" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="813828" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="523287" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-813828"> <div class="moveup"> <div class="ttypography"><p>Div1D can be done in $$$O(n \sqrt{n})$$$. We can use square root decomposition to replace all BITs in tutorial. Since a value in a non-updated position changes by at most one and all values change in the same direction, the full recomputation is only needed in the updated position and we can perform an incremental change in $$$O(1)$$$ for values in each non-updated positions.</p><p><a href="https://codeforces.com/contest/1540/submission/121831547">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-813828 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-813828 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-813828"> <li> <div class="comment"> <table class="comment-table" commentId="834051" commentParentId="813828"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KeyID" style="position: relative;"> <img src='https://userpic.codeforces.org/226684/avatar/10e3671716bf6859.jpg'/> </a> <div><a href="/profile/KeyID" title="Grandmaster KeyID" class="rated-user user-red">KeyID</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/29/2021 12:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-834051" href="?#comment-834051" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-813828" style="font-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="834051" 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="834051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="226684" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-834051"> <div class="moveup"> <div class="ttypography"><p>Realy impressive solution. I'm surprised no stars were given to you until me. Maybe many people didn't get your idea since the solution is actually much more complicated than your brief comment(at least in my opinion). I also wrote a piece of code which used your method but simplified a small part of steps. <a href="https://codeforces.com/contest/1540/submission/127317031">Here</a> it is.</p></div> </div> </div> <div class="reply info"> <a class="comment-834051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-834051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-834051"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="837924" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Harolinch" style="position: relative;"> <img src='https://userpic.codeforces.org/427341/avatar/cf8608aeb55edc95.jpg'/> </a> <div><a href="/profile/Harolinch" title="Pupil Harolinch" class="rated-user user-green">Harolinch</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837924" href="?#comment-837924" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837924" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="427341" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837924"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a> in problem Tree array you said that Fixing a given root r, the expected value of the entire process is obviously the sum of the expected values for a fixed root divided by n.</p><p>why we divide by n at the end ? </p></div> </div> </div> <div class="reply info"> <a class="comment-837924 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837924 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837924"> <li> <div class="comment"> <table class="comment-table" commentId="837928" commentParentId="837924"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837928" href="?#comment-837928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-837924" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837928" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837928"> <div class="moveup"> <div class="ttypography"><p>The calculation is independent based on whichever node that you choose first (it becomes the “root”). Initially you choose one of $$$n$$$ nodes with equal probability so you divide by $$$n$$$ at the end after you’ve summed up the independent expected value after choosing the node $$$i$$$ initially.</p></div> </div> </div> <div class="reply info"> <a class="comment-837928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837928"> </ul> </div> </li> </ul> </div> <br/> <div id="editBox-100805" 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 firstPreview100805 = true; var lastPreviewContent100805 = ''; 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=100805] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=100805] 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-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, 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:33:28</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:'81289372dffb0c4e',t:'MTY5NjcwNzIwOC45MzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1540E
1540
E
ru
E. Вкусные блюда
<div class="problem-statement"><div class="header"><div class="title">E. Вкусные блюда</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>10 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>64 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Обратите внимание на необычное ограничение по памяти.</span></p><p>Есть $$$n$$$ поваров, пронумерованных $$$1, 2, \ldots, n$$$, которые готовят блюда для короля. Повар $$$i$$$ обладает мастерством $$$i$$$ и первоначально приготовил блюдо вкусности $$$a_i$$$, где $$$|a_i| \leq i$$$. У каждого повара есть список поваров, блюда которых он может копировать. Чтобы не допускать распространение плохих привычек, король гарантирует, что повар $$$i$$$ может копировать только у поваров с более высоким мастерством.</p><p>Повара работают над своими блюдами в течение нескольких дней. Каждый день работа над блюдом разбивается на два этапа. </p><ol> <li> В начале каждого дня каждый повар может <span class="tex-font-style-it">выбрать</span>, поработать или нет над своим блюдом, тем самым умножая вкусность своего блюда на свое мастерство ($$$a_i := i \cdot a_i$$$).</li><li> После того как все (кто хотел) поработали над своими блюдами, каждый повар начинает изучать работу других поваров. А именно, для каждого повара $$$j$$$ из списка повара $$$i$$$, повар $$$i$$$ может <span class="tex-font-style-it">выбрать</span>, скопировать ли блюдо повара $$$j$$$, тем самым прибавляя вкусность блюда $$$j$$$ к своему $$$i$$$-му блюду ($$$a_i := a_i + a_j$$$). Можно считать, что все копирования происходят одновременно. Иначе говоря, если повар $$$i$$$ хочет скопировать блюдо повара $$$j$$$, он скопирует вкусность блюдо повара $$$j$$$, полученную в конце этапа $$$1$$$.</li></ol><p>Чтобы угодить королю, каждый повар стремятся максимизировать вкусность <span class="tex-font-style-it">своего</span> блюда.</p><p>Наконец, вам заданы $$$q$$$ запросов. Каждый запрос одно из двух видов:</p><ol> <li> $$$1$$$ $$$k$$$ $$$l$$$ $$$r$$$ — посчитайте сумму вкусностей $$$a_l, a_{l+1}, \ldots, a_{r}$$$ по окончании $$$k$$$-го дня. Так как данное значение может быть велико, выведите его по модулю $$$10^9 + 7$$$. </li><li> $$$2$$$ $$$i$$$ $$$x$$$ — король дарит $$$x$$$ единиц вкусности блюду $$$i$$$-го повара перед началом $$$1$$$-го дня ($$$a_i := a_i + x$$$). Заметим, что королю нравятся вкусные блюда, а потому он дарит положительную вкусность ($$$x &gt; 0$$$). </li></ol><p>Обратите внимание, что запросы типа $$$1$$$ не зависят от других запросов. Точнее говоря, каждый запрос типа $$$1$$$ — это только возможный <span class="tex-font-style-it">сценарий</span> и он не меняет вкусности $$$a_i$$$ для запросов далее. При этом запросы типа $$$2$$$ накапливаются, но меняют только первоначальные значения $$$a_i$$$ блюд. В примечании представлены примеры запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$1 \le n \le 300$$$) — количество поваров.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$-i \le a_i \le i$$$).</p><p>Каждая из следующих $$$n$$$ строк начинается с целого числа $$$c_i$$$ ($$$0 \le c_i &lt; n$$$), означающего количество поваров, у которых $$$i$$$-й повар может копировать блюда. Далее за ним следует $$$c_i$$$ различных числа $$$d$$$ ($$$i &lt; d \le n$$$), обозначающих, что повар $$$i$$$ может копировать у повара $$$d$$$ каждый день во время $$$2$$$-го этапа.</p><p>В следующей строке задано одно целое число $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — количество запросов.</p><p>Каждая из следующих $$$q$$$ строк содержит запрос одного из двух видов: </p><ul> <li> $$$1$$$ $$$k$$$ $$$l$$$ $$$r$$$ ($$$1 \le l \le r \le n$$$; $$$1 \le k \le 1000$$$); </li><li> $$$2$$$ $$$i$$$ $$$x$$$ ($$$1 \le i \le n$$$; $$$1 \le x \le 1000$$$). </li></ul><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> 5 1 0 -2 -2 4 4 2 3 4 5 1 3 1 4 1 5 0 7 1 1 1 5 2 4 3 1 1 1 5 2 3 2 1 2 2 4 2 5 1 1 981 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 57 71 316 278497818 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ниже показаны множества поваров, у которых может копировать каждый из поваров в примере.</p><ul> <li> $$$1$$$: $$$\{2, 3, 4, 5\}$$$ </li><li> $$$2$$$: $$$\{3\}$$$ </li><li> $$$3$$$: $$$\{4\}$$$ </li><li> $$$4$$$: $$$\{5\}$$$ </li><li> $$$5$$$: $$$\emptyset$$$ (ни у кого)</li></ul><p>Далее следует описание первого примера.</p><p>Для первого запроса вида $$$1$$$ первоначальные значения вкусностей равны $$$[1, 0, -2, -2, 4]$$$.</p><p>Значения вкусностей после каждого этапа в первый день: </p><ol> <li> $$$[1, 0, -2, -2, 20]$$$ (повар $$$5$$$ работает над своим блюдом). </li><li> $$$[21, 0, -2, 18, 20]$$$ (повар $$$1$$$ и повар $$$4$$$ копируют у повара $$$5$$$). </li></ol><p>Таким образом, ответ на $$$1$$$-й запрос равен $$$21 + 0 - 2 + 18 + 20 = 57$$$.</p><p>Для $$$5$$$-го запроса ($$$3$$$-й вида $$$1$$$), первоначальные значения вкусностей теперь равны $$$[1, 0, 0, 1, 4]$$$.</p><p><span class="tex-font-style-bf">День 1</span> </p><ol> <li> $$$[1, 0, 0, 4, 20]$$$ (повара $$$4$$$ и $$$5$$$ работают над своими блюдами). </li><li> $$$[25,0, 4, 24, 20]$$$ (повар $$$1$$$ копирует у поваров $$$4$$$ и $$$5$$$, повар $$$3$$$ копирует у повара $$$4$$$, повар $$$4$$$ копирует у повара $$$5$$$). </li></ol><p><span class="tex-font-style-bf">День 2</span> </p><ol> <li> $$$[25, 0, 12, 96, 100]$$$ (все, кроме повара $$$2$$$ работают над своими блюдами). </li><li> $$$[233, 12, 108, 196, 100]$$$ (повар $$$1$$$ копирует у поваров $$$3$$$, $$$4$$$ и $$$5$$$, повар $$$2$$$ у $$$3$$$, повар $$$3$$$ у $$$4$$$, повар $$$4$$$ у повара $$$5$$$).<p>Таким образом, ответ на $$$5$$$-й запрос равен $$$12+108+196=316$$$. </p></li></ol><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="1b6ece9699addd1fcd2a21fe8196bf8c"/> <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="73d6e96a98bbd7625389194b3afaf471bd9b24fb"/> <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='1b6ece9699addd1fcd2a21fe8196bf8c'>&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%2F1540%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='1b6ece9699addd1fcd2a21fe8196bf8c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1540">Codeforces Round 728 (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='1b6ece9699addd1fcd2a21fe8196bf8c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1540/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Произведение матриц, определитель, правило Крамера, системы линейных уравнений"> матрицы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *3500 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1b6ece9699addd1fcd2a21fe8196bf8c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1027091"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1b6ece9699addd1fcd2a21fe8196bf8c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1027091"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92093" title="Codeforces Round #728" target="_blank">Codeforces Round #728 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13928" resourceName="Codeforces Round #728" resourceManual="true" src="//codeforces.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/92199" title="Tutorial" target="_blank">Tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13942" 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/1540">Задачи</a></li> <li><a href="/contest/1540/submit">Отослать</a></li> <li><a href="/contest/1540/my">Мои посылки</a></li> <li><a href="/contest/1540/status">Статус</a></li> <li><a href="/contest/1540/hacks">Взломы</a></li> <li><a href="/contest/1540/room/1">Комната</a></li> <li><a href="/contest/1540/standings">Положение</a></li> <li><a href="/contest/1540/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2d5b43d0ae8ffeeec73237d7380046c95e2f6217"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>10 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>64 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Обратите внимание на необычное ограничение по памяти.</span></p><p>Есть $$$n$$$ поваров, пронумерованных $$$1, 2, \ldots, n$$$, которые готовят блюда для короля. Повар $$$i$$$ обладает мастерством $$$i$$$ и первоначально приготовил блюдо вкусности $$$a_i$$$, где $$$|a_i| \leq i$$$. У каждого повара есть список поваров, блюда которых он может копировать. Чтобы не допускать распространение плохих привычек, король гарантирует, что повар $$$i$$$ может копировать только у поваров с более высоким мастерством.</p><p>Повара работают над своими блюдами в течение нескольких дней. Каждый день работа над блюдом разбивается на два этапа. </p><ol> <li> В начале каждого дня каждый повар может <span class="tex-font-style-it">выбрать</span>, поработать или нет над своим блюдом, тем самым умножая вкусность своего блюда на свое мастерство ($$$a_i := i \cdot a_i$$$).</li><li> После того как все (кто хотел) поработали над своими блюдами, каждый повар начинает изучать работу других поваров. А именно, для каждого повара $$$j$$$ из списка повара $$$i$$$, повар $$$i$$$ может <span class="tex-font-style-it">выбрать</span>, скопировать ли блюдо повара $$$j$$$, тем самым прибавляя вкусность блюда $$$j$$$ к своему $$$i$$$-му блюду ($$$a_i := a_i + a_j$$$). Можно считать, что все копирования происходят одновременно. Иначе говоря, если повар $$$i$$$ хочет скопировать блюдо повара $$$j$$$, он скопирует вкусность блюдо повара $$$j$$$, полученную в конце этапа $$$1$$$.</li></ol><p>Чтобы угодить королю, каждый повар стремятся максимизировать вкусность <span class="tex-font-style-it">своего</span> блюда.</p><p>Наконец, вам заданы $$$q$$$ запросов. Каждый запрос одно из двух видов:</p><ol> <li> $$$1$$$ $$$k$$$ $$$l$$$ $$$r$$$ — посчитайте сумму вкусностей $$$a_l, a_{l+1}, \ldots, a_{r}$$$ по окончании $$$k$$$-го дня. Так как данное значение может быть велико, выведите его по модулю $$$10^9 + 7$$$. </li><li> $$$2$$$ $$$i$$$ $$$x$$$ — король дарит $$$x$$$ единиц вкусности блюду $$$i$$$-го повара перед началом $$$1$$$-го дня ($$$a_i := a_i + x$$$). Заметим, что королю нравятся вкусные блюда, а потому он дарит положительную вкусность ($$$x &gt; 0$$$). </li></ol><p>Обратите внимание, что запросы типа $$$1$$$ не зависят от других запросов. Точнее говоря, каждый запрос типа $$$1$$$ — это только возможный <span class="tex-font-style-it">сценарий</span> и он не меняет вкусности $$$a_i$$$ для запросов далее. При этом запросы типа $$$2$$$ накапливаются, но меняют только первоначальные значения $$$a_i$$$ блюд. В примечании представлены примеры запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$1 \le n \le 300$$$) — количество поваров.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$-i \le a_i \le i$$$).</p><p>Каждая из следующих $$$n$$$ строк начинается с целого числа $$$c_i$$$ ($$$0 \le c_i &lt; n$$$), означающего количество поваров, у которых $$$i$$$-й повар может копировать блюда. Далее за ним следует $$$c_i$$$ различных числа $$$d$$$ ($$$i &lt; d \le n$$$), обозначающих, что повар $$$i$$$ может копировать у повара $$$d$$$ каждый день во время $$$2$$$-го этапа.</p><p>В следующей строке задано одно целое число $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — количество запросов.</p><p>Каждая из следующих $$$q$$$ строк содержит запрос одного из двух видов: </p><ul> <li> $$$1$$$ $$$k$$$ $$$l$$$ $$$r$$$ ($$$1 \le l \le r \le n$$$; $$$1 \le k \le 1000$$$); </li><li> $$$2$$$ $$$i$$$ $$$x$$$ ($$$1 \le i \le n$$$; $$$1 \le x \le 1000$$$). </li></ul><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> 5 1 0 -2 -2 4 4 2 3 4 5 1 3 1 4 1 5 0 7 1 1 1 5 2 4 3 1 1 1 5 2 3 2 1 2 2 4 2 5 1 1 981 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 57 71 316 278497818 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ниже показаны множества поваров, у которых может копировать каждый из поваров в примере.</p><ul> <li> $$$1$$$: $$$\{2, 3, 4, 5\}$$$ </li><li> $$$2$$$: $$$\{3\}$$$ </li><li> $$$3$$$: $$$\{4\}$$$ </li><li> $$$4$$$: $$$\{5\}$$$ </li><li> $$$5$$$: $$$\emptyset$$$ (ни у кого)</li></ul><p>Далее следует описание первого примера.</p><p>Для первого запроса вида $$$1$$$ первоначальные значения вкусностей равны $$$[1, 0, -2, -2, 4]$$$.</p><p>Значения вкусностей после каждого этапа в первый день: </p><ol> <li> $$$[1, 0, -2, -2, 20]$$$ (повар $$$5$$$ работает над своим блюдом). </li><li> $$$[21, 0, -2, 18, 20]$$$ (повар $$$1$$$ и повар $$$4$$$ копируют у повара $$$5$$$). </li></ol><p>Таким образом, ответ на $$$1$$$-й запрос равен $$$21 + 0 - 2 + 18 + 20 = 57$$$.</p><p>Для $$$5$$$-го запроса ($$$3$$$-й вида $$$1$$$), первоначальные значения вкусностей теперь равны $$$[1, 0, 0, 1, 4]$$$.</p><p><span class="tex-font-style-bf">День 1</span> </p><ol> <li> $$$[1, 0, 0, 4, 20]$$$ (повара $$$4$$$ и $$$5$$$ работают над своими блюдами). </li><li> $$$[25,0, 4, 24, 20]$$$ (повар $$$1$$$ копирует у поваров $$$4$$$ и $$$5$$$, повар $$$3$$$ копирует у повара $$$4$$$, повар $$$4$$$ копирует у повара $$$5$$$). </li></ol><p><span class="tex-font-style-bf">День 2</span> </p><ol> <li> $$$[25, 0, 12, 96, 100]$$$ (все, кроме повара $$$2$$$ работают над своими блюдами). </li><li> $$$[233, 12, 108, 196, 100]$$$ (повар $$$1$$$ копирует у поваров $$$3$$$, $$$4$$$ и $$$5$$$, повар $$$2$$$ у $$$3$$$, повар $$$3$$$ у $$$4$$$, повар $$$4$$$ у повара $$$5$$$).<p>Таким образом, ответ на $$$5$$$-й запрос равен $$$12+108+196=316$$$. </p></li></ol><p>Можно показать, что на каждом описанном шаге все повара действовали оптимально.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c6e8bf6100a5',t:'MTY5NjY2NzM3My4yNzAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u043c\u0430\u0442\u0440\u0438\u0446, \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u044c, \u043f\u0440\u0430\u0432\u0438\u043b\u043e \u041a\u0440\u0430\u043c\u0435\u0440\u0430, \u0441\u0438\u0441\u0442\u0435\u043c\u044b \u043b\u0438\u043d\u0435\u0439\u043d\u044b\u0445 \u0443\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u0439", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043c\u0430\u0442\u0440\u0438\u0446\u044b", "*3500"]
https://codeforces.com/blog/entry/92199
<!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="ea33d124a1ff874ace73f937748d303e"/> <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="Codeforces Round #728 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #728 Editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='ea33d124a1ff874ace73f937748d303e'>&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%2F92199">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='ea33d124a1ff874ace73f937748d303e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:31:32</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:31:32</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='ea33d124a1ff874ace73f937748d303e'/> <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/PurpleCrayon">PurpleCrayon</a></li> <li class="current selectedLava"><a href="/blog/PurpleCrayon">Blog</a></li> <li><a href="/teams/with/PurpleCrayon">Teams</a></li> <li><a href="/submissions/PurpleCrayon">Submissions</a></li> <li><a href="/groups/with/PurpleCrayon">Groups</a></li> <li><a href="/contests/with/PurpleCrayon">Contests</a></li> <li><a href="/contests/writer/PurpleCrayon">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/PurpleCrayon" style="text-decoration:none;color:black !important;">PurpleCrayon's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="92809"> <div class="title"> <a href="/blog/entry/92199"> <p>Codeforces Round #728 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a>, <a href="/topic/92809/en10">history</a>, <span class="format-humantime" title="Jun/25/2021 20:44">2 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><a href="/contest/1541/problem/A" title="Codeforces Round 728 (Div. 2)">1541A - Pretty Permutations</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The parity (whether $$$n$$$ is odd or even) matters.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Swapping two adjacent cats keeps both of them close to their original location and changes both of their locations.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>If $$$n$$$ is even, the optimal distance is $$$n$$$, and if $$$n$$$ is odd the optimal distance is $$$n+1$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541A">Tutorial is loading...</div></div></div><p><a href="/contest/1541/problem/B" title="Codeforces Round 728 (Div. 2)">1541B - Pleasant Pairs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>$$$i+j \leq 2 \cdot n$$$</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The number of pairs $$$(a, b)$$$ such that $$$a \cdot b \leq x$$$ is $$$O(x log x)$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/A" title="Codeforces Round 728 (Div. 1)">1540A - Great Graphs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What's the minimum value that an edge from $$$a$$$ to $$$b$$$ can be?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use edges with negative value whenever you can.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The sum of the values of edges with positive weight must be $$$\geq$$$ the maximum value in the array.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540A">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Tree Array</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Fix the initial node chosen and root the tree there, what is the contribution of each pair of nodes?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Nothing matters besides the path from node $$$a$$$ to node $$$b$$$, and the initially chosen node $$$r$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>You are given two stacks of size $$$a_1$$$ and $$$a_2$$$. In a single step, you randomly choose a stack to remove a single item from. What is the probability that $$$a_1$$$ becomes $$$0$$$ before $$$a_2$$$? Can you extend this argument for an arbitrary probability $$$p$$$ to remove from one of the two stacks, and a probability of $$$1-2p$$$ to do nothing?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/C2" title="Codeforces Round 728 (Div. 1)">1540C2 - Converging Array (Hard Version)</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What are the invariants? The monovariants?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What is the prefix sum array of the converged array? What is the difference array of the converged array?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you conducted the process on a prefix of size $$$1$$$, then of size $$$2$$$, and on and on?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How many values $$$x$$$ are actually interesting?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540C2">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Inverse Inversions</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The answer is always unique.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Try to figure out what the location of the $$$i$$$-th element would be if you only looked at the first $$$i$$$ elements, then the first $$$i+1$$$, etc. to find an $$$O(nq)$$$ solution.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use sqrt decomposition to optimize it.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540D">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/E" title="Codeforces Round 728 (Div. 1)">1540E - Tasty Dishes</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How much does each chef's initial dish contribute at time $$$k$$$?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you really, really wanted to use matrix exponentiation?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How can you multiply some vectors by a matrix in $$$O(N)$$$ time? (go back to linear algebra class)</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Decompose into linear combinations of eigenvectors.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540E">Tutorial is loading...</div></div></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/1540" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 1)</a> </span> </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/1541" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-191295-92809").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "191295", blogEntryId: "92199", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-92809"><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'>+96</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-92809"><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/PurpleCrayon"><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/PurpleCrayon"> PurpleCrayon </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="Jun/25/2021 20:44">2 years ago</span> </li> <li> <a href="/blog/entry/92199#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/92199#comments"> 170 </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="100805"> <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 (136)</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="808750" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808750" href="?#comment-808750" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808750" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-66" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-66</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808750"> <div class="moveup"> <div class="ttypography"><p>PURPLECRAYON ORZ</p></div> </div> </div> <div class="reply info"> <a class="comment-808750 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808750 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808750"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808751" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hbarp" style="position: relative;"> <img src='https://userpic.codeforces.org/1387715/avatar/c727a810db6ffb66.jpg'/> </a> <div><a href="/profile/hbarp" title="Candidate Master hbarp" class="rated-user user-violet">hbarp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808751" href="?#comment-808751" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808751" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="1387715" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-83</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808751"> <div class="moveup"> <div class="ttypography"><p>Damn, so orz round. <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Мастер PurpleCrayon">PurpleCrayon</a> orz</p></div> </div> </div> <div class="reply info"> <a class="comment-808751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808751"> <li> <div class="comment"> <table class="comment-table" commentId="808805" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/naman1601" style="position: relative;"> <img src='https://userpic.codeforces.org/1703219/avatar/d63fc523dc05fda8.jpg'/> </a> <div><a href="/profile/naman1601" title="Master naman1601" class="rated-user user-orange">naman1601</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808805" href="?#comment-808805" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808805" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-51" data-commentUserId="1703219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-51</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808805"> <div class="moveup"> <div class="ttypography"><p>yeah, amazing problemset, not speedforces at all :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808805 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808805 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808805"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808817" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LOVELY_BOY_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/LOVELY_BOY_" title="Newbie LOVELY_BOY_" class="rated-user user-gray">LOVELY_BOY_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808817" href="?#comment-808817" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-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="808817" 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="808817" class="CommentVoteFrame" data-commentRating="35" data-commentUserId="2089809" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808817"> <div class="moveup"> <div class="ttypography"><p>LOL <a class="rated-user user-blue" href="/profile/hbarp" title="Эксперт hbarp">hbarp</a>,even you didn't participate in the contest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808817 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808817 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808817"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808753" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DontLookBack" style="position: relative;"> <img src='https://userpic.codeforces.org/1534766/avatar/4eacdc5f9758fc28.jpg'/> </a> <div><a href="/profile/DontLookBack" title="Specialist DontLookBack" class="rated-user user-cyan">DontLookBack</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808753" href="?#comment-808753" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808753" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1534766" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808753"> <div class="moveup"> <div class="ttypography"><p>I am curious, how many div2 testers solved D?</p></div> </div> </div> <div class="reply info"> <a class="comment-808753 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808753 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808753"> <li> <div class="comment"> <table class="comment-table" commentId="808826" commentParentId="808753"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/highonjuice" style="position: relative;"> <img src='https://userpic.codeforces.org/1457566/avatar/f7988dd2af03d38b.jpg'/> </a> <div><a href="/profile/highonjuice" title="Pupil highonjuice" class="rated-user user-green">highonjuice</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808826" href="?#comment-808826" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808753" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808826" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1457566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808826"> <div class="moveup"> <div class="ttypography"><p>like 2 ppl, it was hard for me</p></div> </div> </div> <div class="reply info"> <a class="comment-808826 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808826 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808826"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808757" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tlatoani" style="position: relative;"> <img src='https://userpic.codeforces.org/614001/avatar/598b4e8358aad1b4.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/Tlatoani" title="Grandmaster Tlatoani" class="rated-user user-red">Tlatoani</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:18">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808757" href="?#comment-808757" style="font-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="808757" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="808757" class="CommentVoteFrame" data-commentRating="121" data-commentUserId="614001" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+121</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808757"> <div class="moveup"> <div class="ttypography"><h4>Alternate solution to <a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Инвертируем инверсии</a></h4><p>(Read the first nontrivial paragraph of the editorial before reading this alternate solution)</p><p>Let $$$p_r(k) = x$$$ denote that of the numbers $$$p(1), \ldots, p(r)$$$ in sorted order, $$$p(k)$$$ is equal to the $$$x$$$th of these numbers. We will take a decomposition strategy just as the editorial does, though our strategy will be different. We will divide $$$[1, n]$$$ into blocks of length $$$b$$$. For each block covering some interval $$$[l, r]$$$, we will store $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>This means that for any $$$k$$$, if we know $$$p_r(k)$$$ for some block $$$[l, r]$$$, then we can determine $$$p_{r'}(k)$$$ for the block $$$[l', r']$$$ immediately to the right by binary searching on the numbers stored for $$$[l', r']$$$. Therefore, we can perform queries in $$$O\left(\frac n b \lg b\right)$$$.</p><p>We now need to figure out updates. There are probably simple ways to perform updates in $$$O(b\lg b)$$$, but this yields an overall runtime of $$$O(q\sqrt n \lg n)$$$ which is too slow.</p><p>Therefore, we can instead store each block as a segment tree. For each range $$$[l, r]$$$ in the segment tree we store the same thing we store for the whole block: $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>We then have to quickly merge two intervals. We can merge two intervals of length $$$\lambda$$$ in $$$O(\lambda \lg \lambda)$$$ by doing binary search just as we did above, but this still only yields $$$O(b\lg b)$$$ update overall. However, these $$$\lambda$$$ binary searches can be optimized using two pointers to $$$O(\lambda)$$$, making the overall update $$$O(b)$$$.</p><p>We thus have $$$O\left(\frac n b \lg b\right)$$$ query and $$$O(b)$$$ update. Therefore, we can choose $$$b = \sqrt{n\lg n}$$$ to attain an overall runtime of $$$O\left(q\sqrt{n\lg n}\right)$$$ just as the editorial does.</p><p><a href="https://codeforces.com/contest/1540/submission/120611645">Submission in Kotlin</a></p><p><a href="https://codeforces.com/contest/1540/submission/120612729">Submission in C++</a></p><p>It is interesting to note that this solution is quite fast. At the time of writing this update, the C++ version is the fastest correct submission (and runs under 1 second!) and the Kotlin version is faster than the vast majority of submissions.</p></div> </div> </div> <div class="reply info"> <a class="comment-808757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808757"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808765" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardcode229" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardcode229" title="Newbie hardcode229" class="rated-user user-gray">hardcode229</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808765" href="?#comment-808765" style="font-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="808765" 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="808765" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1635180" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808765"> <div class="moveup"> <div class="ttypography"><p>The 3rd hint for the second problem is same as that of the first problem, is it related or a mistake? <strong>UPD:</strong> it is corrected.</p></div> </div> </div> <div class="reply info"> <a class="comment-808765 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808765 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808765"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808769" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/peanut" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/peanut" title="Specialist peanut" class="rated-user user-cyan">peanut</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:24">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808769" href="?#comment-808769" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808769" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="1167233" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+22</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808769"> <div class="moveup"> <div class="ttypography"><p>speedforces.</p></div> </div> </div> <div class="reply info"> <a class="comment-808769 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808769 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808769"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808781" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/graphs_11" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/graphs_11" title="Specialist graphs_11" class="rated-user user-cyan">graphs_11</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808781" href="?#comment-808781" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808781" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1610110" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808781"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">Problem B Detailed Explanation</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808781 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808781 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808781"> <li> <div class="comment"> <table class="comment-table" commentId="809069" commentParentId="808781"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:40">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809069" href="?#comment-809069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808781" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809069" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809069"> <div class="moveup"> <div class="ttypography"><p>Thank you, very well explained</p></div> </div> </div> <div class="reply info"> <a class="comment-809069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809069"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808790" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PC_E1052" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PC_E1052" title="Pupil PC_E1052" class="rated-user user-green">PC_E1052</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808790" href="?#comment-808790" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808790" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="811219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808790"> <div class="moveup"> <div class="ttypography"><p>c was too easy, d was too hard. but d was very nice problem though. </p></div> </div> </div> <div class="reply info"> <a class="comment-808790 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808790 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808790"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808793" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808793" href="?#comment-808793" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808793" class="CommentVoteFrame" data-commentRating="58" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+58</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808793"> <div class="moveup"> <div class="ttypography"><p>Paging <a class="rated-user user-legendary" href="/profile/ecnerwala" title="Легендарный гроссмейстер ecnerwala"><span class="legendary-user-first-letter">e</span>cnerwala</a> to explain his solution to D1E if he'd like. It seems offline?</p></div> </div> </div> <div class="reply info"> <a class="comment-808793 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808793 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808793"> <li> <div class="comment"> <table class="comment-table" commentId="808979" commentParentId="808793"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ecnerwala" 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/ecnerwala" title="Legendary Grandmaster ecnerwala" class="rated-user user-legendary"><span class="legendary-user-first-letter">e</span>cnerwala</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808979" href="?#comment-808979" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808793" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808979" class="CommentVoteFrame" data-commentRating="40" data-commentUserId="57502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808979"> <div class="moveup"> <div class="ttypography"><p>My solution is $$$O(K N^3 + QN)$$$. I just precomputed the coefficient of each $$$a_i$$$ for each prefix-range for each number of days since person $$$i$$$ becomes positive (only $$$1000$$$ possible days) in $$$O(N \cdot K \cdot N^2)$$$, and then summed up the appropriate ones to answer each query in $$$O(N)$$$. It's written in the offline style to use only $$$O(KN)$$$ memory at a time (grouped by $$$a_i$$$) instead of $$$O(KN^2)$$$.</p><p>My passing submission is just $$$KN^3 / 6$$$ instead of the $$$KN^3$$$ I submitted in contest :'(</p><p>If you guys wanted to prevent this, $$$K$$$ could've been much higher, like $$$1e18$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808979 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808979 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808979"> <li> <div class="comment"> <table class="comment-table" commentId="809002" commentParentId="808979"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809002" href="?#comment-809002" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808979" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809002" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809002"> <div class="moveup"> <div class="ttypography"><p>:( I knew of this solution (it’s why ML is tight) but I didn’t realize that it could be done offline with small memory. Of course $$$K$$$ higher is obvious solution but main issue is that the extra modulos from binary exponentiation make it very hard to pass in Java without allowing other unoptimal solutions through such as precomputing inverses of the matrix. Probably $$$k=10^5$$$ would’ve been a better choice. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-809002 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809002 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809002"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808795" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zukonit14" style="position: relative;"> <img src='https://userpic.codeforces.org/1192187/avatar/5afd49be87fb87d9.jpg'/> </a> <div><a href="/profile/zukonit14" title="Expert zukonit14" class="rated-user user-blue">zukonit14</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808795" href="?#comment-808795" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808795" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1192187" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808795"> <div class="moveup"> <div class="ttypography"><p>Does Div2 D deserved to be D Problem? According to me it should've been Div2 E.</p></div> </div> </div> <div class="reply info"> <a class="comment-808795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808795"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808796" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mangat_angad" style="position: relative;"> <img src='https://userpic.codeforces.org/1449578/avatar/d3cadb0c26e0c11f.jpg'/> </a> <div><a href="/profile/mangat_angad" title="Specialist mangat_angad" class="rated-user user-cyan">mangat_angad</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808796" href="?#comment-808796" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808796" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1449578" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808796"> <div class="moveup"> <div class="ttypography"><p>I feel like such an idiot for not being able to understand problem C (Div2). For some reason I thought the nodes were connected like this — 1-&gt;2-&gt;3-&gt;....-&gt;N and that we had to minimise answer by adding other edges (of negative weight in case they dont give a negative cycle) to this graph.</p></div> </div> </div> <div class="reply info"> <a class="comment-808796 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808796 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808796"> <li> <div class="comment"> <table class="comment-table" commentId="808896" commentParentId="808796"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808896" href="?#comment-808896" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808796" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808896" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808896"> <div class="moveup"> <div class="ttypography"><p>But that's exactly what I did, and the final answer is the sum of the array — sum of all subarrays. <a href="https://codeforces.com/contest/1541/submission/120611950">120611950</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808896 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808896 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808896"> <li> <div class="comment"> <table class="comment-table" commentId="808941" commentParentId="808896"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808941" href="?#comment-808941" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808896" style="font-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="808941" 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="808941" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808941"> <div class="moveup"> <div class="ttypography"><p>No, that's not what you did. To compute the answer via the method described above, you would have to compute how many elements are lesser than the current element at any given iteration and add them and also keep and their count using a Fenwick tree/ BIT. That's the incorrect approach though because sorting would be more optimal.</p></div> </div> </div> <div class="reply info"> <a class="comment-808941 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808941 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808941"> <li> <div class="comment"> <table class="comment-table" commentId="808952" commentParentId="808941"> <tr> <td class="left"> <div style="position: absolute; left: 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/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808952" href="?#comment-808952" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808941" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808952" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808952"> <div class="moveup"> <div class="ttypography"><p>Sorry if I misunderstood things. mangat_angad only mentioned adding negative weighed edges to the 1-&gt;2-&gt;3-&gt;...N graph, which is what I thought to arrive at my solution. The array I mentioned is indeed sorted and formed by distance differences which are the weights in the 1-&gt;2-&gt;3-&gt;...N graph. Unfortunately I'm still too noob to understand the tree structures you mentioned.</p></div> </div> </div> <div class="reply info"> <a class="comment-808952 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808952 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808952"> <li> <div class="comment"> <table class="comment-table" commentId="808955" commentParentId="808952"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808955" href="?#comment-808955" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808952" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808955" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808955"> <div class="moveup"> <div class="ttypography"><p>Nothing unfortunate about it, logic trumps everything </p></div> </div> </div> <div class="reply info"> <a class="comment-808955 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808955 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808955"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808797" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808797" href="?#comment-808797" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808797" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808797"> <div class="moveup"> <div class="ttypography"><p>Just want to apologize to authors for the stupidest question, I misread the task..</p></div> </div> </div> <div class="reply info"> <a class="comment-808797 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808797 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808797"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808813" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808813" href="?#comment-808813" style="font-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="808813" 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="808813" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808813"> <div class="moveup"> <div class="ttypography"><p>Can someone tell me the meaning of this line in problem Div2D/Div1B<br /></p> <blockquote><p>Note that, until reaching, l every possible process still has the same probability of reaching b before a. Therefore, we can assume that the process has reached l and calculate the probability from there.</p> </blockquote><p>What same probability are they talking about?</p></div> </div> </div> <div class="reply info"> <a class="comment-808813 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808813 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808813"> <li> <div class="comment"> <table class="comment-table" commentId="808831" commentParentId="808813"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808831" href="?#comment-808831" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808813" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808831" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808831"> <div class="moveup"> <div class="ttypography"><p>Here's what it's trying to say:</p><p>Suppose we start by marking the root. To mark a or b, we must first mark the lca, so we may assume that the lca has just been marked.</p></div> </div> </div> <div class="reply info"> <a class="comment-808831 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808831 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808831"> <li> <div class="comment"> <table class="comment-table" commentId="808840" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808840" href="?#comment-808840" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808840" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808840"> <div class="moveup"> <div class="ttypography"><p>And what does this line mean? <em>&quot;The problem can be rephrased as having two stacks of size dist(l,a) and dist(l,b) with an arbitrary p to remove a node from one of the two stack (and 1−2p to nothing) and finding the probability that dist(l,b) reaches zero before dist(l,a).&quot;</em></p></div> </div> </div> <div class="reply info"> <a class="comment-808840 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808840 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808840"> <li> <div class="comment"> <table class="comment-table" commentId="808857" commentParentId="808840"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808857" href="?#comment-808857" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808840" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808857" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808857"> <div class="moveup"> <div class="ttypography"><p>Once you've reached the lca $$$l$$$, in a single step you either step closer to $$$a$$$, step closer to $$$b$$$, or step closer to neither.</p></div> </div> </div> <div class="reply info"> <a class="comment-808857 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808857 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808857"> <li> <div class="comment"> <table class="comment-table" commentId="808862" commentParentId="808857"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808862" href="?#comment-808862" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808857" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808862" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808862"> <div class="moveup"> <div class="ttypography"><p>Can you add implementation for this problem please?</p></div> </div> </div> <div class="reply info"> <a class="comment-808862 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808862 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808862"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808849" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808849" href="?#comment-808849" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808849" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808849"> <div class="moveup"> <div class="ttypography"><p>So, we mark lca first (of course). But why wouldn't it affect the final probability of reaching b before a? I mean, why is it sufficient to calculate the probability after marking lca?</p></div> </div> </div> <div class="reply info"> <a class="comment-808849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808849"> <li> <div class="comment"> <table class="comment-table" commentId="808873" commentParentId="808849"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808873" href="?#comment-808873" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808849" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808873" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808873"> <div class="moveup"> <div class="ttypography"><p>Before marking the lca, there is no way to make more progress towards $$$b$$$ than $$$a$$$ or vice versa. The subset of marked vertices also does not change the probability of moving towards $$$a$$$ or $$$b$$$ after reaching the lca because we're choosing uniformly at random and exactly two vertices are of interest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808873 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808873 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808873"> <li> <div class="comment"> <table class="comment-table" commentId="808883" commentParentId="808873"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808883" href="?#comment-808883" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808873" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808883" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808883"> <div class="moveup"> <div class="ttypography"><p>Now I get it. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808883 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808883 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808883"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808814" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808814" href="?#comment-808814" style="font-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="808814" 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="808814" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808814"> <div class="moveup"> <div class="ttypography"><p>So, my Solution for <strong>Div1 Problem B</strong> / <strong>Div2 Problem D</strong> / <strong>1540B — Tree Array</strong>:</p><p>Chose two Nodes $$$A$$$ and $$$B$$$ with $$$A&gt;B$$$. </p><p><strong>First DFS:</strong> Find the path from $$$A$$$ to $$$B$$$. I call it $$$path_p$$$. On $$$path_p$$$ mark the distance to $$$B$$$ for each node. </p><p><strong>Second DFS:</strong> For each remaining node $$$N$$$ find the shortest path to $$$path_p$$$. It will hit it at some node of the $$$path_p$$$ which has some distance $$$D$$$ marked on it. We mark $$$N$$$ with $$$D$$$. (See comment below for image.)</p><p><strong>Calculation:</strong> For each node $$$N$$$ we can calculate $$$P_i$$$. $$$P_i$$$ is the probability to reach Node $$$B$$$ before we reach Node $$$A$$$. We sum $$$P_i$$$ for each node. $$$P_i$$$ is also the probability, that the pair of Nodes $$$A$$$ and $$$B$$$ with starting node $$$N$$$ will contribute to the inversion sum. </p><p><strong>Iteration:</strong> We need to repeat this for each pair $$$A$$$ and $$$B$$$. In the end we divide the answer by $$$n$$$, the amount of nodes (the probability to start with Node $$$N$$$). </p><p>This algorithm is $$$O(N^3)$$$. See my Solution <a href="/contest/1540/submission/120603369" title="Посылка 120603369 от OleschY">120603369</a></p> <div class="spoiler"><b class="spoiler-title">How to calculate P_i</b><div class="spoiler-content" style="display: none;"><p>I wrote myself a small helper DP-program to find the regularities. Let $$$D$$$ be the Distance between $$$A$$$ and $$$B$$$ and $$$d$$$ be the distance from the node $$$N$$$ to $$$B$$$. My educated guess was: $$$P_i=\frac{\sum_{i=0}^{d-1}\binom{D-1}{i} }{2^{D-1}}$$$</p> <div class="spoiler"><b class="spoiler-title">Helper Program</b><div class="spoiler-content" style="display: none;"><p>It checks for a path of some length for each Intervall $$$[A,B]$$$ which is already visited, what the probability to reach one node before the other is. </p> <pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; int solve(int n) { vector&lt;vector&lt;double&gt;&gt; dp(n, vector&lt;double&gt;(n, 0)); for(int i = 0; i &lt; n; ++i) { dp[0][i] = 1; dp[i][n - 1] = 0; } dp[0][n - 1] = -1; for(int w = n; w &gt;= 0; w--) { for(int i = 1; i + w &lt; n - 1; i++) { int l = i; int r = w + i; dp[l][r] = 0.5 * (dp[l - 1][r] + dp[l][r + 1]); } } cout &lt;&lt; n &lt;&lt; &quot;\n\n&quot;; for(int i = 0; i &lt; n; i++) { cout &lt;&lt; dp[i][i]*(1&lt;&lt;(n-2)) &lt;&lt; &quot;\n&quot;; } cout &lt;&lt; &quot;\n\n\n\n&quot;; return 0; } //====================== // Technical stuff //====================== int main() { int ntest = 12; for(int test = 2; test &lt; ntest; ++test) { solve(test); } return 0; } </code></pre></div></div></div></div></div> </div> </div> <div class="reply info"> <a class="comment-808814 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808814 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808814"> <li> <div class="comment"> <table class="comment-table" commentId="808843" commentParentId="808814"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808843" href="?#comment-808843" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808814" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808843" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808843"> <div class="moveup"> <div class="ttypography"><p>Can you explain your solution in a little bit more detail? :')</p></div> </div> </div> <div class="reply info"> <a class="comment-808843 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808843 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808843"> <li> <div class="comment"> <table class="comment-table" commentId="808869" commentParentId="808843"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808869" href="?#comment-808869" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808843" style="font-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="808869" 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="808869" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808869"> <div class="moveup"> <div class="ttypography"><p>Oof, I can give you an image, that shows how the distances from the two DFS are distributed on an example. You can see Nodes $$$A$$$ and $$$B$$$ and the numbers are the distances we write into the nodes. </p><p><img alt=" " src="/predownloaded/d8/2f/d82f98ecd2c1b4bd15b3c40e62476f6ae2741a64.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>If you have specific questions about some steps go ahead and ask. </p></div> </div> </div> <div class="reply info"> <a class="comment-808869 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808869 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808869"> <li> <div class="comment"> <table class="comment-table" commentId="810069" commentParentId="808869"> <tr> <td class="left"> <div style="position: absolute; left: 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/Mrajaryan" style="position: relative;"> <img src='https://userpic.codeforces.org/1377953/avatar/e904b3a3a2eac1ad.jpg'/> </a> <div><a href="/profile/Mrajaryan" title="Newbie Mrajaryan" class="rated-user user-gray">Mrajaryan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 15:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810069" href="?#comment-810069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808869" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810069" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1377953" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810069"> <div class="moveup"> <div class="ttypography"><p>what does the dp states mean in your helper program? I am unable to understand. Can you please explain?</p></div> </div> </div> <div class="reply info"> <a class="comment-810069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810069"> <li> <div class="comment"> <table class="comment-table" commentId="810097" commentParentId="810069"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 18:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810097" href="?#comment-810097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-810069" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810097"> <div class="moveup"> <div class="ttypography"><p>You have Nodes $$$1$$$ through $$$N$$$, neighbouring IDs are connected. The state $$$dp[l][r]$$$ is the probability, that node $$$N$$$ will be reached before node $$$1$$$ with all the nodes $$$l$$$ through $$$r$$$ marked already. Obviously $$$dp[1][x]=0$$$ and $$$dp[x][N]=1$$$ ($$$dp[1][N]$$$ can't happen). The recurrence is $$$dp[l][r]=(dp[l-1][r]+dp[l][r+1])/2$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-810097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808818" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808818" href="?#comment-808818" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808818" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808818"> <div class="moveup"> <div class="ttypography"><p>I can't grasp the editorial of Div 2 D/ Div 1 B. Can somebody provide a more intuitive explanation?</p></div> </div> </div> <div class="reply info"> <a class="comment-808818 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808818 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808818"> <li> <div class="comment"> <table class="comment-table" commentId="808821" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:45">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808821" href="?#comment-808821" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808821" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808821"> <div class="moveup"> <div class="ttypography"><p>same :(</p></div> </div> </div> <div class="reply info"> <a class="comment-808821 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808821 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808821"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808861" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808861" href="?#comment-808861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808861" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808861"> <div class="moveup"> <div class="ttypography"><p>Step 1. use linearity of expectation. The answer is</p> <center>$$$\sum_{a&lt;b} P(b\text{ appears before }a). $$$</center><p>Step 2: Observe that if we start by marking a vertex $$$c$$$ on the path between $$$a$$$ and $$$b$$$, and suppose the next marked vertex on the path is $$$d$$$. Then, the probability that $$$d$$$ is between $$$c$$$ and $$$a$$$ and the probability that $$$d$$$ is between $$$c$$$ and $$$b$$$ are both $$$1/2$$$. This is because there are only two choices for $$$d$$$ and we're choosing uniformly at random. This means that the answer only depends on $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p><p>Step 3: run a dp to calculate the probability that we mark $$$b$$$ before $$$a$$$ given $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808861"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808833" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808833" href="?#comment-808833" style="font-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="808833" 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="808833" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-72" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-72</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808833"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin &gt;&gt; t; while(t--){ int n; cin &gt;&gt; n; long long arr[n]; for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0; for(int i = 0; i &lt; n — 1; i++){ for(int j = arr[i] — 2 — i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } } } cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;; } return 0; }</p><p>/* Accepted code A different approach using arrays (as I don't know what vectors are, haven't read that) I hope this is a optimal approach. Any suggestions related to this are whole-heartedly welcomed. Also, please guide me how could I have optimized the code to a much extent. Thanks in advance! Keep programming! */</p></div> </div> </div> <div class="reply info"> <a class="comment-808833 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808833 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808833"> <li> <div class="comment"> <table class="comment-table" commentId="808844" commentParentId="808833"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808844" href="?#comment-808844" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808833" style="font-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="808844" 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="808844" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-35" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808844"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-808844 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808844 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808844"> <li> <div class="comment"> <table class="comment-table" commentId="808863" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808863" href="?#comment-808863" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808863" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808863"> <div class="moveup"> <div class="ttypography"><p>Not studied yet, I'm still a beginner, but planning to start soon. Thanks for the guidance.</p></div> </div> </div> <div class="reply info"> <a class="comment-808863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808863"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808879" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808879" href="?#comment-808879" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808879" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808879"> <div class="moveup"> <div class="ttypography"><p>once upon a time, I also did problems while not know what vectors are. sad times :'(</p></div> </div> </div> <div class="reply info"> <a class="comment-808879 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808879 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808879"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808926" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808926" href="?#comment-808926" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808926" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808926"> <div class="moveup"> <div class="ttypography"><p>There's no issue in not knowing vectors. Yes they are important I agree but not knowing vectors should not be discouraged. I became expert here without knowing anything about vectors plus he is a beginner so he shouldn't be discouraged like this.</p></div> </div> </div> <div class="reply info"> <a class="comment-808926 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808926 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808926"> <li> <div class="comment"> <table class="comment-table" commentId="808927" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Tech.Maniac" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Tech.Maniac" title="Expert Tech.Maniac" class="rated-user user-blue">Tech.Maniac</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808927" href="?#comment-808927" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808927" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1242860" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808927"> <div class="moveup"> <div class="ttypography"><p>+1, I agree with you. Same I was expert last year solely using arrays</p></div> </div> </div> <div class="reply info"> <a class="comment-808927 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808927 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808927"> <li> <div class="comment"> <table class="comment-table" commentId="809201" commentParentId="808927"> <tr> <td class="left"> <div style="position: absolute; left: 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/Yash.Amin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Yash.Amin" title="Specialist Yash.Amin" class="rated-user user-cyan">Yash.Amin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809201" href="?#comment-809201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808927" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809201" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-28" data-commentUserId="1226462" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-28</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809201"> <div class="moveup"> <div class="ttypography"><p>Bas kar bsdk kitna jhooth bolega</p></div> </div> </div> <div class="reply info"> <a class="comment-809201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809201"> <li> <div class="comment"> <table class="comment-table" commentId="809215" commentParentId="809201"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809215" href="?#comment-809215" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809215" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809215"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-blue" href="/profile/Yash.Amin" title="Эксперт Yash.Amin">Yash.Amin</a> Could you please refrain from using foul language on educational discussions. Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-809215 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809215 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809215"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808928" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808928" href="?#comment-808928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808928" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808928"> <div class="moveup"> <div class="ttypography"><p>Ah my bad, I did not want to come across as being arrogant, but I was genuinely confused that some people did not know vectors although they are using C++.</p></div> </div> </div> <div class="reply info"> <a class="comment-808928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808928"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808839" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamkiller04" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dreamkiller04" title="Newbie dreamkiller04" class="rated-user user-gray">dreamkiller04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808839" href="?#comment-808839" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2089608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808839"> <div class="moveup"> <div class="ttypography"><p>Please add implementations too.</p></div> </div> </div> <div class="reply info"> <a class="comment-808839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808839"> <li> <div class="comment"> <table class="comment-table" commentId="809106" commentParentId="808839"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809106" href="?#comment-809106" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808839" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809106" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809106"> <div class="moveup"> <div class="ttypography"><p>Simply running two loops and checking every case would give a TLE. So, we might want to minimize the number of operations. For this, we would only consider the cases where the sum of indices is a multiple of an element.</p><p>For this, we would first create two loops, one within the other, first loop iterating i from 0 to (n — 1) with an incrementation of 1. By observation, we can see that the first index for which the sum of indices will be a multiple of arr[i] is (arr[i] — 2 — i).</p><p>So, in the nested loop we will run j = (arr[i] — 2 — i) till (n — 1) with an incrementation of arr[i]. We would ignore the cases where j &lt; 0 or j &gt;= n.</p><p>Finally, we need to check for how many cases this holds (arr[i] * arr[j] = i + j + 2 and j &gt; i).</p><p>Suggestions are welcomed!</p></div> </div> </div> <div class="reply info"> <a class="comment-809106 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809106 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809106"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808842" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808842" href="?#comment-808842" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808842" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-64" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-64</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808842"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){</p><p>ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);</p><p>int t;</p><p>cin &gt;&gt; t;</p><p>while(t--){</p><p>int n;</p> <pre>cin &gt;&gt; n;</pre><p>long long arr[n];</p> <pre>for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0;</pre><p>for(int i = 0; i &lt; n — 1; i++){</p> <pre>for(int j = arr[i] &amp;mdash; 2 &amp;mdash; i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } }</pre><p>}</p><p>cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;;</p><p>}</p> <pre>return 0;</pre><p>}</p><p>/* Accepted code</p><p>A different approach using arrays (as I don't know what vectors are, haven't read that)</p><p>I hope this is a optimal approach.</p><p>Any suggestions related to this are whole-heartedly welcomed.</p><p>Also, please guide me how could I have optimized the code to a much extent.</p><p>Thanks in advance!</p><p>Keep programming! </p><p>*/</p></div> </div> </div> <div class="reply info"> <a class="comment-808842 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808842 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808842"> <li> <div class="comment"> <table class="comment-table" commentId="808851" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808851" href="?#comment-808851" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808851" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808851"> <div class="moveup"> <div class="ttypography"><p>Use spoilers for writing codes, please!</p></div> </div> </div> <div class="reply info"> <a class="comment-808851 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808851 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808851"> <li> <div class="comment"> <table class="comment-table" commentId="808870" commentParentId="808851"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808870" href="?#comment-808870" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808851" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808870" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808870"> <div class="moveup"> <div class="ttypography"><p>Actually, this is my first comment. Don't know much of this stuff as of now, but I'll surely take care of it the very next time.</p></div> </div> </div> <div class="reply info"> <a class="comment-808870 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808870 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808870"> <li> <div class="comment"> <table class="comment-table" commentId="809760" commentParentId="808870"> <tr> <td class="left"> <div style="position: absolute; left: 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/sus" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sus" title="Pupil sus" class="rated-user user-green">sus</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 05:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809760" href="?#comment-809760" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808870" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809760" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1749651" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809760"> <div class="moveup"> <div class="ttypography"><p>what problem is your code for</p></div> </div> </div> <div class="reply info"> <a class="comment-809760 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809760 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809760"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808884" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sevlll777" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sevlll777" title="Grandmaster sevlll777" class="rated-user user-red">sevlll777</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808884" href="?#comment-808884" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808884" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="839333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808884"> <div class="moveup"> <div class="ttypography"><p>NICE CODESTYLE!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-808884 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808884 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808884"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809084" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cj2021" style="position: relative;"> <img src='https://userpic.codeforces.org/1927237/avatar/b64ff59bd9dcf385.jpg'/> </a> <div><a href="/profile/cj2021" title="Newbie cj2021" class="rated-user user-gray">cj2021</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809084" href="?#comment-809084" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809084" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1927237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809084"> <div class="moveup"> <div class="ttypography"><p>What is &amp;mdash?</p><p>Just curious to know as haven't seen it before.</p></div> </div> </div> <div class="reply info"> <a class="comment-809084 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809084 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809084"> <li> <div class="comment"> <table class="comment-table" commentId="809097" commentParentId="809084"> <tr> <td class="left"> <div style="position: absolute; left: 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/klahsiv" style="position: relative;"> <img src='https://userpic.codeforces.org/1590145/avatar/1bf86ae3d48e55b.jpg'/> </a> <div><a href="/profile/klahsiv" title="Expert klahsiv" class="rated-user user-blue">klahsiv</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809097" href="?#comment-809097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809084" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590145" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809097"> <div class="moveup"> <div class="ttypography"><p>it is minus (-).</p></div> </div> </div> <div class="reply info"> <a class="comment-809097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808848" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/willy108" style="position: relative;"> <img src='https://userpic.codeforces.org/1439320/avatar/d7f79ed4e8b32e9a.jpg'/> </a> <div><a href="/profile/willy108" title="Master willy108" class="rated-user user-orange">willy108</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808848" href="?#comment-808848" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808848" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="1439320" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808848"> <div class="moveup"> <div class="ttypography"><p>Div2 B can also be done in O(NsqrtN). We know that for a given pair of indeces i+j &lt; 2n, so any pair that a[i] * a[j] &lt; 2n will have to have one of the two terms be &lt;= sqrt(n) (with some off by one errors of course). So the algorithm is to store an array of pairs [array value, index] and sort that array by the value. If the array value is &lt;= sqrt(2n) we can naively loop over the rest of the array in O(n) time and check (be careful about overcount), and if the value is &gt; sqrt(n), we can ignore it. This works since when a[i] * a[j] &lt; 2n one of a[i] or a[j] has to be &lt;= sqrt(2n) and as a result, every pair will be counted.</p></div> </div> </div> <div class="reply info"> <a class="comment-808848 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808848 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808848"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808860" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bcollet" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bcollet" title="Master bcollet" class="rated-user user-orange">bcollet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808860" href="?#comment-808860" style="font-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="808860" 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="808860" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="858059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808860"> <div class="moveup"> <div class="ttypography"><p>I don't understand in div1 C why it's prefix of b, in the case i=3 we have $$$a_1+a_2+a_3=f_1+f_1+b_1+f_1+b_1+b_2$$$ so $$$f_1=(ap_i-2b_1-b_2)$$$ I believe the general formula is something in the taste of $$$f_1=(ap_i-ibp_{i-1}+bpt_{i-1})/i$$$ where bpt_i=b_1+2b_2+...+ib_i, I think I miss something<br />Edit: corrected</p></div> </div> </div> <div class="reply info"> <a class="comment-808860 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808860 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808860"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808865" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ParsaS" style="position: relative;"> <img src='https://userpic.codeforces.org/1590150/avatar/dc2d8c002d2c5e1e.jpg'/> </a> <div><a href="/profile/ParsaS" title="Candidate Master ParsaS" class="rated-user user-violet">ParsaS</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808865" href="?#comment-808865" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808865" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590150" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808865"> <div class="moveup"> <div class="ttypography"><p>Nice problems. thanks for almost fast editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-808865 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808865 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808865"> <li> <div class="comment"> <table class="comment-table" commentId="808871" commentParentId="808865"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/E404_Not_Found" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/E404_Not_Found" title="Expert E404_Not_Found" class="rated-user user-blue">E404_Not_Found</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808871" href="?#comment-808871" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808865" style="font-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="808871" 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="808871" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1662858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808871"> <div class="moveup"> <div class="ttypography"><p>Yes thanks for fast editorial :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808871 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808871 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808871"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808890" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vikash_8090_b" style="position: relative;"> <img src='https://userpic.codeforces.org/1969032/avatar/a0f23c893ae54e74.jpg'/> </a> <div><a href="/profile/vikash_8090_b" title="Newbie vikash_8090_b" class="rated-user user-gray">vikash_8090_b</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808890" href="?#comment-808890" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808890" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="1969032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808890"> <div class="moveup"> <div class="ttypography"><p>is there anyone who can't even solve one question of today's contest ..</p></div> </div> </div> <div class="reply info"> <a class="comment-808890 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808890 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808890"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808892" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808892" href="?#comment-808892" style="font-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="808892" 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="808892" class="CommentVoteFrame" data-commentRating="-6" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808892"> <div class="moveup"> <div class="ttypography"><p>Deleted :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808892 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808892 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808892"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808918" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prituladima" style="position: relative;"> <img src='https://userpic.codeforces.org/116750/avatar/ca46d0256a294b26.jpg'/> </a> <div><a href="/profile/prituladima" title="Pupil prituladima" class="rated-user user-green">prituladima</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808918" href="?#comment-808918" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808918" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="116750" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808918"> <div class="moveup"> <div class="ttypography"><p>Please explain div2c/div1a problem a little bit more. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808918 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808918 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808918"> <li> <div class="comment"> <table class="comment-table" commentId="808921" commentParentId="808918"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808921" href="?#comment-808921" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808918" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808921" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808921"> <div class="moveup"> <div class="ttypography"><p>Try out this <a href="https://youtube.com/c/MagentaCobra">channel</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808921 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808921 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808921"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808950" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jakab922" style="position: relative;"> <img src='https://userpic.codeforces.org/53532/avatar/f9515e974f3ebcb1.jpg'/> </a> <div><a href="/profile/jakab922" title="Specialist jakab922" class="rated-user user-cyan">jakab922</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808950" href="?#comment-808950" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808950" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="53532" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808950"> <div class="moveup"> <div class="ttypography"><p>I don't really understand the need for a recursive function for the stack emptying probabilities in <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a>. I mean given that you have a stack of size <code>n</code> and and <code>m</code> you can basically have an array of size <code>n + m</code> filled with <code>0</code>s and <code>1</code>s where <code>0</code> at the <code>i</code>th place means that the <code>i</code>th element was taken from the first stack. Any such array which has <code>n</code> <code>0</code>s and <code>m</code> <code>1</code>s correspond to one process and it's easy to see that whoever takes the last spot in the array gets emptied later which gives an easy way to calculate the probabilities. Namely $$$\binom{n + m - 1}{n - 1} / \binom{n + m}{n}$$$ for the first and similar to the other. </p></div> </div> </div> <div class="reply info"> <a class="comment-808950 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808950 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808950"> <li> <div class="comment"> <table class="comment-table" commentId="808959" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cuom1999" style="position: relative;"> <img src='https://userpic.codeforces.org/253776/avatar/934152bc42a0b10c.jpg'/> </a> <div><a href="/profile/cuom1999" title="Grandmaster cuom1999" class="rated-user user-red">cuom1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808959" href="?#comment-808959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="253776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808959"> <div class="moveup"> <div class="ttypography"><p>If $$$m=2$$$ and $$$n=1$$$, your approach gives $$$\frac{1}{3}$$$. The correct answer should be $$$\frac{1}{4}$$$. </p><p>P/S: I'm also curious if there is any combinatoric approach for this,<a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808959"> <li> <div class="comment"> <table class="comment-table" commentId="809004" commentParentId="808959"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809004" href="?#comment-809004" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809004" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809004"> <div class="moveup"> <div class="ttypography"><p>I would guess that there’s no easy closed form. You can evaluate in $$$O(n)$$$ however by counting right up paths from $$$(a,0)$$$ to $$$(x,y)$$$ for all $$$a$$$ and multiplying by $$$2^{-steps}$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-809004 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809004 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809004"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809366" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/geekpradd" style="position: relative;"> <img src='https://userpic.codeforces.org/367430/avatar/427394aa7f5a63a0.jpg'/> </a> <div><a href="/profile/geekpradd" title="Candidate Master geekpradd" class="rated-user user-violet">geekpradd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809366" href="?#comment-809366" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809366" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="367430" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809366"> <div class="moveup"> <div class="ttypography"><p>The problem with this is that all the possibilities are not equilikely, consider $$$m=2, n=1$$$ and let $$$1$$$ denote entries from the stack of size $$$n$$$. Then the probability of obtaining $$$100$$$ is $$$1/2$$$, while obtaining $$$010$$$ and $$$001$$$ has a probability of $$$1/4$$$. Your approach assumes a uniform prior probability (in which case the answer is indeed $$$1/3$$$ whereas here it is $$$1/4$$$ which is the probability of getting $$$001$$$)</p></div> </div> </div> <div class="reply info"> <a class="comment-809366 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809366 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809366"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thunderboltz" style="position: relative;"> <img src='https://userpic.codeforces.org/1170396/avatar/4f017b259605bc5c.jpg'/> </a> <div><a href="/profile/thunderboltz" title="Newbie thunderboltz" class="rated-user user-gray">thunderboltz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808951" href="?#comment-808951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170396" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808951"> <div class="moveup"> <div class="ttypography"><p>Problem Div2C/Div1A, Plz somebody explain 3rd hint. I didn't get why this condition must be true </p><p><code>The sum of the values of edges with positive weight must be ≥ the maximum value in the array.</code></p></div> </div> </div> <div class="reply info"> <a class="comment-808951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808951"> <li> <div class="comment"> <table class="comment-table" commentId="808995" commentParentId="808951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808995" href="?#comment-808995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808995" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808995"> <div class="moveup"> <div class="ttypography"><p>I like to think about C this way: The cheapest node is the root, and the most expensive node, X, is the one with the highest value, D. Therefore no matter how we make our edges, we need at least 1 path from node to X with distance D. So let's build 1 single edge of positive weight from 1 to X with weight D.</p><p>Now from node X, all other nodes are &lt;= D. We can use negative edges to go there. Now the problem just becomes &quot;assign as many negative edges as possible&quot; to the rest of the nodes. </p></div> </div> </div> <div class="reply info"> <a class="comment-808995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808995"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808971" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808971" href="?#comment-808971" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808971" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808971"> <div class="moveup"> <div class="ttypography"><p>In problem <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a> I agree with everything up to:</p> <blockquote><p>Once l is reached, we now note that the probability that the process &quot;gets closer&quot; to b is always equal to the probability of getting closer to a.</p> </blockquote><p>I agree with this quote if it was about each individual set of marked nodes and single step for them. Because for any individual set of marked nodes, those probabilities is just one over the number of options at the moment. But I don't understand why I should forget about everything else what happens with other parts of tree, because after single step which is neither towards <strong>a</strong> neither towards <strong>b</strong>, the number of options (nodes we can mark on next step) may change.</p></div> </div> </div> <div class="reply info"> <a class="comment-808971 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808971 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808971"> <li> <div class="comment"> <table class="comment-table" commentId="809006" commentParentId="808971"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809006" href="?#comment-809006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808971" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809006" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809006"> <div class="moveup"> <div class="ttypography"><p>That is correct, but to see how it stays the same you can think of it inductively. Use strong induction and assume probability is the same no matter what the state of the tree is. Then from $$$(x,y)$$$ you always have an equal probability of ending up in one of the two states you can transition to because $$$p$$$ is always the same. Every scenario you enter one state, there’s another scenario with the same probability that enters the other state. So, the probability of entering one of the two states is the same as the other, thus $$$0.5$$$. Hopefully that makes things more clear.</p></div> </div> </div> <div class="reply info"> <a class="comment-809006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809006"> <li> <div class="comment"> <table class="comment-table" commentId="809113" commentParentId="809006"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809113" href="?#comment-809113" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809006" style="font-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="809113" 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="809113" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809113"> <div class="moveup"> <div class="ttypography"><p>Oh thanks, it's clear now. So, base of induction is when only <strong>l</strong> reached, and we can show that probability to make step towards <strong>a</strong> and <strong>b</strong> is same because for each individual set you can go from <strong>l</strong> to <strong>b</strong> instead of going from <strong>l</strong> into <strong>a</strong>, using exactly same steps in between (those steps which doesn't change distances to <strong>a</strong> and <strong>b</strong>). And similar holds for next steps.</p></div> </div> </div> <div class="reply info"> <a class="comment-809113 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809113 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809113"> <li> <div class="comment"> <table class="comment-table" commentId="821713" commentParentId="809113"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 08:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821713" href="?#comment-821713" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809113" style="font-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="821713" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="821713" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-821713"> <div class="moveup"> <div class="ttypography"><p>Can you explain this?</p><p>Assume $$$X$$$ is initially node we chose. Then define a function $$$g$$$ :</p><p>$$$g[a][b][STATE]$$$ = probability to reach a before b while state of the tree we reach is $$$STATE$$$, and $$$a$$$, $$$b$$$ is length of path.</p><p><img alt=" " src="/predownloaded/c2/32/c232d053fe3fbd1dedc06e56db58a7c139157987.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>follow the image, I can see : $$$g[a][b][STATE_x] = \frac{1}{4} (g[a][b][STATE_d] + g[a][b][STATE_e] + g[a — 1][b][closer_a] + g[a][b — 1][closer_b])$$$</p><p>It can easy see that the probability can change. Or I wrong in some where?</p></div> </div> </div> <div class="reply info"> <a class="comment-821713 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821713 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821713"> <li> <div class="comment"> <table class="comment-table" commentId="821861" commentParentId="821713"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 18:25">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821861" href="?#comment-821861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821713" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="821861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-821861"> <div class="moveup"> <div class="ttypography"><p>I'll hide my long explanation under spoiler</p> <div class="spoiler"><b class="spoiler-title">horrible wall of text</b><div class="spoiler-content" style="display: none;"><p>To put things into words, I want to define some things. First, suppose we marked some $$$s_1, s_2, s_3 ... s_k$$$ vertices in exact this order. Then, let $$$P(s)$$$ to be probability to mark them in this sequence. It can be decomposed into $$$P(s) = p_1 \cdot p_2 \cdot p_3 \cdot ... \cdot p_k$$$ where $$$p_i = 1/o_{i-1}$$$ where $$$o_i$$$ is number of options at step $$$i$$$ — number of opened vertices, except $$$p_0 = 1/n$$$, or $$$o_0 = n$$$.</p><p>Then, let $$$l = LCA(a, b)$$$ where $$$LCA$$$ is lowest common ancestor. Then, let $$$x_v$$$ to be some sort of 'cost'. For each $$$v$$$ on path between $$$a$$$ and $$$l$$$ it will be distance to $$$l$$$, and $$$-1$$$ everywhere else. Similarly, for each $$$v$$$ on path between $$$b$$$ and $$$l$$$ let $$$y_v$$$ to be distance to $$$l$$$ and $$$-1$$$ everywhere else. Let</p> <center>$$$ A(s) = \max\limits_{v\in s}x_v \\ B(s) = \max\limits_{v\in s}y_v $$$</center><p>Then $$$A(s)$$$ is equal to how far we reach $$$a$$$, and $$$B(s)$$$ is equal to how far we reach $$$b$$$. Let say we are in situation $$$(A(s), B(s))$$$ after marking $$$s$$$, and therefore situation is pair of numbers. Situation $$$(-1,-1)$$$ corresponds that no vertex is marked on path from $$$a$$$ to $$$b$$$. Situation $$$(0,0)$$$ corresponds to only $$$l$$$ marked on path from $$$a$$$ to $$$b$$$. And situation $$$(1,0)$$$ corresponds to $$$l$$$ and single vertex towards $$$a$$$ is marked.</p><p>Finally, let say sequence of marks $$$s$$$ reached state $$$(A(s), B(s))$$$ if either $$$A(s) = x_{s_k}$$$ or $$$B(s) = y_{s_k}$$$, in other words, last vertex is on path from $$$a$$$ to $$$b$$$ and it did change situation.</p><p>Now, what we want to prove is following:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha+1,\beta)} P(s) = \sum\limits_{s\;reached\;(\alpha,\beta+1)} P(s)$$$</center><p><strong>For some fixed</strong> $$$s_1$$$, which is root we chosen. And the way we prove it is that $$$s$$$ that is reached $$$(\alpha+1,\beta)$$$ consists of $$$u$$$ that reached $$$(\alpha,\beta)$$$ plus additional steps: $$$w$$$ plus $$$s_k$$$. So $$$s = u..w..s_k$$$ where $$$..$$$ is concatenation. It's easy to see what none of vertices from $$$w$$$ is on path from $$$a$$$ to $$$b$$$. Also, it's easy to see that we could instead of choosing $$$s_k$$$ could choose vertex $$$z$$$ towards $$$b$$$, and it would have same probability. In other words $$$P(s) = P(u..w..z)$$$. And this $$$u..w..z$$$ should reach state $$$(\alpha, \beta+1)$$$. So it should be in right side sum of our equation we want to prove.</p><p>So, for any $$$s$$$ from left sum, we can make $$$s'$$$ from right sum in unique way, and it will have same $$$P(s) = P(s')$$$. Similarly, for any $$$s$$$ from right sum, we can make $$$s'$$$ from left sum in unique way, and it will have same $$$P(s) = P(s')$$$. So this is bijection, and each element from left sum corresponds to element from right sum with same value, so those sums should have same value. Therefore it's equality.</p><p>Initially I wanted to trim $$$s$$$ from $$$(\alpha+1,\beta)$$$ to $$$(\alpha,\beta)$$$ and show similar thing based on following sum:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha,\beta)} P(s)$$$</center><p>Which is probability to reach state $$$(\alpha, \beta)$$$, but luckily it didn't required. I'll use notation $$$P(reach(\alpha, \beta))$$$ for this probability.</p><p>Thing that is not covered though: why this equality can be translated into probability $$$= 1/2$$$? Well, from $$$(\alpha, \beta)$$$ you eventually will reach either $$$(\alpha+1,\beta)$$$ or $$$(\alpha,\beta+1)$$$, so you can see this as example of Law of total probability. $$$P(reach(\alpha, \beta)) = P(reach (\alpha+1, \beta)) + P(reach (\alpha, \beta+1))$$$, because events $$$(\alpha+1,\beta)$$$ and $$$(\alpha,\beta+1)$$$ are disjoint events given $$$(\alpha, \beta)$$$ is reached. And we proved they have equal probability so $$$P(reach(\alpha, \beta)) = 2\cdot P(reach (\alpha+1, \beta))$$$, so $$$P(reach (\alpha+1, \beta)) = 1/2\cdot P(reach(\alpha, \beta))$$$ which we actually use.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-821861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821861"> <li> <div class="comment"> <table class="comment-table" commentId="822027" commentParentId="821861"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/28/2021 13:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822027" href="?#comment-822027" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821861" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="822027" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822027"> <div class="moveup"> <div class="ttypography"><p>Oh, sorry, there is one missing part. We proved $$$P(reached(\alpha+1,\beta))=P(reached(\alpha,\beta+1))$$$ <strong>given</strong> $$$(\alpha,\beta)$$$ is reached, but this is actually what we need. This <strong>given</strong> condition is what I missed. Without <strong>given</strong> we could reach $$$(\alpha+1,\beta)$$$ from reaching $$$(\alpha+1,\beta-1)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-822027 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822027 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822027"> <li> <div class="comment"> <table class="comment-table" commentId="822370" commentParentId="822027"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 13:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822370" href="?#comment-822370" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822027" style="font-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="822370" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="822370" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822370"> <div class="moveup"> <div class="ttypography"><p>Thanks for amz explain. I realize that I had some missunderstand in the way we calc $$$P(reach\ A\ before\ B)$$$</p><p>This's exactly what in my mind one day ago: let $$$s = ...a...b...$$$ where $$$a$$$ and $$$b$$$ is node $$$a$$$ and node $$$b$$$, &quot;$$$...$$$&quot; mean some node between them which we chose them in exactly that order, or in other word, $$$s$$$ is state represent what we chose (exact in this order) I think $$$P(reach\ A\ before\ B)$$$ (or $$$P(A&lt;B)$$$) must be calculate in this way :</p><p>$$$P(A&lt;B) = \sum_{\substack{all\ s\ which\ a&lt;b}} P(s)$$$</p><p>But unfortunately, it's wrong (may be, or I still missunderstanding)</p><p>$$$P(A) = \sum_{\substack{all\ B[i]\ \subseteq\ A}} P(B[i])$$$ if and only if all $$$B[i]$$$ are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-822370 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822370 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822370"> <li> <div class="comment"> <table class="comment-table" commentId="822755" commentParentId="822370"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 22:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822755" href="?#comment-822755" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822370" style="font-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="822755" 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="822755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822755"> <div class="moveup"> <div class="ttypography"><p>$$$P(A &lt; B)$$$ in your terms is exactly what we need (if a = A and b = B).</p><p>I don't understand last formula, everything else looks fine.</p><p>And to find $$$P(A &lt; B)$$$ we use fact above and calculate all possible ways to reach $$$a$$$ earlier than $$$b$$$ we use $$$(\alpha, \beta)$$$ states using my notation: you either get $$$\alpha$$$ equal to dist to $$$a$$$ when $$$\beta$$$ = 0, or $$$\beta$$$ = 1, or 2, or 3...</p> <center>$$$ P(A &lt; B) = \\ =\sum\limits_{i=0}^{dist(b,l)}P(reach(dist(a,l),i)\;given\; reached(dist(a,l)-1,i)) \\ = \sum\limits_{i=0}^{dist(b,l)}P(reached(dist(a,l)-1,i))\cdot \frac{1}{2} $$$</center><p>Or you can rephrase task into other task with two kind of balls. What probability to remove all balls of one kind earlier than other, if you pick one or other kind of ball with probability 1/2.</p></div> </div> </div> <div class="reply info"> <a class="comment-822755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822755"> </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="808983" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/xsc" style="position: relative;"> <img src='https://userpic.codeforces.org/343/avatar/9eaf243b1eb8c3d4.jpg'/> </a> <div><a href="/profile/xsc" title="Specialist xsc" class="rated-user user-cyan">xsc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808983" href="?#comment-808983" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808983" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="343" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808983"> <div class="moveup"> <div class="ttypography"><p>Div2 D, O(N^4) solution <a href="/contest/1541/submission/120623566" title="Посылка 120623566 от xsc">120623566</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808983 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808983 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808983"> <li> <div class="comment"> <table class="comment-table" commentId="809278" commentParentId="808983"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DavidXu_JJ" style="position: relative;"> <img src='https://userpic.codeforces.org/2003708/avatar/623dc8036b4e9d72.jpg'/> </a> <div><a href="/profile/DavidXu_JJ" title="Expert DavidXu_JJ" class="rated-user user-blue">DavidXu_JJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809278" href="?#comment-809278" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808983" style="font-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="809278" 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="809278" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2003708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809278"> <div class="moveup"> <div class="ttypography"><p>Your code really helps me a lot in debugging,thanks.</p><p>By the way,it's weired that I get Wrong6 when I try to optimize to O(N^3*logN) by binary search on tree.</p><p>I have tested my function on other online judge and my function seems to be correct.</p></div> </div> </div> <div class="reply info"> <a class="comment-809278 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809278 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809278"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809018" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ducati" style="position: relative;"> <img src='https://userpic.codeforces.org/699102/avatar/eff3c352646e914e.jpg'/> </a> <div><a href="/profile/ducati" title="Grandmaster ducati" class="rated-user user-red">ducati</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 03:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809018" href="?#comment-809018" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809018" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="699102" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809018"> <div class="moveup"> <div class="ttypography"><p>Although Div.2 D is harder than ever, in my opinion, it's such a useful and excellent problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-809018 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809018 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809018"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809046" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KanishkGoel" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/KanishkGoel" title="Expert KanishkGoel" class="rated-user user-blue">KanishkGoel</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809046" href="?#comment-809046" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809046" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1917239" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809046"> <div class="moveup"> <div class="ttypography"><p>Is it usual for people to post solutions online during the contest like this channel? <a href="https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ">https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809046 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809046 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809046"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809051" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809051" href="?#comment-809051" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809051"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain why this submission <a href="/contest/1541/submission/120562335" title="Посылка 120562335 от Karnania7201">120562335</a> is failing for Div2 B? It would be a great help.</p></div> </div> </div> <div class="reply info"> <a class="comment-809051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809051"> <li> <div class="comment"> <table class="comment-table" commentId="809076" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809076" href="?#comment-809076" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809076" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809076"> <div class="moveup"> <div class="ttypography"><p>Bro you did not included the condition that i and j should be different i.e (i != j) because it is given in question that no are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-809076 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809076 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809076"> <li> <div class="comment"> <table class="comment-table" commentId="809079" commentParentId="809076"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:08">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809079" href="?#comment-809079" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809076" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809079" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809079"> <div class="moveup"> <div class="ttypography"><p>I think its covered as I started j from i+1. I tried that explicitly too but it didn't work. I wrote the same idea in a different way and it worked but this kind of implementation is not working.</p></div> </div> </div> <div class="reply info"> <a class="comment-809079 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809079 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809079"> <li> <div class="comment"> <table class="comment-table" commentId="809082" commentParentId="809079"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809082" href="?#comment-809082" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809079" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809082" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809082"> <div class="moveup"> <div class="ttypography"><p>yeah, you are right, I run your code using vector instead of creating memeset it worked fine, i guess there is some problem in that. <a href="https://codeforces.com/contest/1541/submission/120633207">120633207</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809082 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809082 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809082"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809081" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_NICkk" style="position: relative;"> <img src='https://userpic.codeforces.org/1543175/avatar/6084dd87f2c1cad9.jpg'/> </a> <div><a href="/profile/_NICkk" title="Expert _NICkk" class="rated-user user-blue">_NICkk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809081" href="?#comment-809081" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809081" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1543175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809081"> <div class="moveup"> <div class="ttypography"><p>Only fault in your code is that you didn't used memset correctly </p><p>I just changed your memset with this &quot; memset(ind, 0, sizeof(ind)) &quot; and it worked perfectly fine</p></div> </div> </div> <div class="reply info"> <a class="comment-809081 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809081 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809081"> <li> <div class="comment"> <table class="comment-table" commentId="809091" commentParentId="809081"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:37">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809091" href="?#comment-809091" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809081" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809091" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809091"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot to both of you. I shouldn't have used it without properly knowing about it. </p></div> </div> </div> <div class="reply info"> <a class="comment-809091 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809091 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809091"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809064" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vrintle" style="position: relative;"> <img src='https://userpic.codeforces.org/1991777/avatar/24d9007095afbbb6.jpg'/> </a> <div><a href="/profile/vrintle" title="Master vrintle" class="rated-user user-orange">vrintle</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809064" href="?#comment-809064" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809064" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1991777" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809064"> <div class="moveup"> <div class="ttypography"><p>Instead of $$$a_i \cdot a_j \leq 2n$$$, we could also check $$$a_i \cdot a_j \leq i+n$$$ which is a bit faster ($$$ \sim 62ms$$$).</p></div> </div> </div> <div class="reply info"> <a class="comment-809064 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809064 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809064"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809066" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809066" href="?#comment-809066" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809066" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809066"> <div class="moveup"> <div class="ttypography"><p>can anyone explain B. pleasant pairs more easy words?? </p></div> </div> </div> <div class="reply info"> <a class="comment-809066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809066"> <li> <div class="comment"> <table class="comment-table" commentId="809067" commentParentId="809066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809067" href="?#comment-809067" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809067" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809067"> <div class="moveup"> <div class="ttypography"><p>And also what is ask in 3rd question i cant understand what asked in it</p></div> </div> </div> <div class="reply info"> <a class="comment-809067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809067"> <li> <div class="comment"> <table class="comment-table" commentId="809070" commentParentId="809067"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809070" href="?#comment-809070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809067" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809070"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">https://www.youtube.com/watch?v=xCj_ZR5kENo</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809098" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809098" href="?#comment-809098" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809098" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809098"> <div class="moveup"> <div class="ttypography"><p>For those who are searching for a simple solution for great Graphs problems in O (nlogn). <a href="https://codeforces.com/contest/1541/submission/120600816">https://codeforces.com/contest/1541/submission/120600816</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809098 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809098 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809098"> <li> <div class="comment"> <table class="comment-table" commentId="809119" commentParentId="809098"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fjvzr" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/fjvzr" title="Newbie fjvzr" class="rated-user user-gray">fjvzr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809119" href="?#comment-809119" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809098" style="font-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="809119" 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="809119" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1623986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809119"> <div class="moveup"> <div class="ttypography"><p>Bro can u explain this soln????? i thought of taking all pairs that give negative edges except for the adjacent pairs.... bt getting wrong ans in 3rd 4th test case.....</p><p>while(n&gt;2) { sum-=(n-2)*(llabs(a[j]-a[i])); n--; // n = size i++; // i = 0 j--; // j = n-1 } cout&lt;&lt;sum&lt;&lt;endl;</p><p><a href="https://codeforces.com/contest/1541/submission/120636509">mysoln</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809119 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809119 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809119"> <li> <div class="comment"> <table class="comment-table" commentId="809124" commentParentId="809119"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809124" href="?#comment-809124" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809119" style="font-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="809124" 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="809124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809124"> <div class="moveup"> <div class="ttypography"><p>My solution is simple. First sort the array. </p><p>Then start connecting adjacent values with their differences. This way sum of all edges with positive weight will be same as the sum of adjacent differences in the array.</p><p>After that start making negative edges for every i. So each i will have i negative edges. Where negative weight is same as -(arr[i] — arr[j]).</p><p>Instead of search it for every j I have formula as (prefixsum till i) — arr[i]*i</p></div> </div> </div> <div class="reply info"> <a class="comment-809124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809124"> <li> <div class="comment"> <table class="comment-table" commentId="809132" commentParentId="809124"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809132" href="?#comment-809132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809124" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809132"> <div class="moveup"> <div class="ttypography"><p>can you tell me why are we sorting the array for a particular node call it x we need to add a negative weight from x to 1 , x to 2 x to 3 till x to x-1 keeping in mind the the path sum doesn't become negative so why are we sorting the array</p></div> </div> </div> <div class="reply info"> <a class="comment-809132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809132"> <li> <div class="comment"> <table class="comment-table" commentId="809135" commentParentId="809132"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809135" href="?#comment-809135" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809135" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809135"> <div class="moveup"> <div class="ttypography"><p>We are sorting values only once so as to connect neighboring nodes with minimum values,i.e. difference b/w consecutive values.<br /> From this sum of positive edges will be minimum.</p></div> </div> </div> <div class="reply info"> <a class="comment-809135 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809135 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809135"> <li> <div class="comment"> <table class="comment-table" commentId="809139" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809139" href="?#comment-809139" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809139" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809139"> <div class="moveup"> <div class="ttypography"><p>ohhh thanks I got it</p></div> </div> </div> <div class="reply info"> <a class="comment-809139 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809139 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809139"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809145" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809145" href="?#comment-809145" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809145" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809145"> <div class="moveup"> <div class="ttypography"><p>My solution is working now I only needed to sort the array my code would have been accepted during the contest :(</p></div> </div> </div> <div class="reply info"> <a class="comment-809145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809145"> </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="809116" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ken_KaNeKi_997" style="position: relative;"> <img src='https://userpic.codeforces.org/1737228/avatar/50ceb845253df5d4.jpg'/> </a> <div><a href="/profile/Ken_KaNeKi_997" title="Newbie Ken_KaNeKi_997" class="rated-user user-gray">Ken_KaNeKi_997</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809116" href="?#comment-809116" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809116" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1737228" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809116"> <div class="moveup"> <div class="ttypography"><p>can anyone explain div2 B plz</p></div> </div> </div> <div class="reply info"> <a class="comment-809116 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809116 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809116"> <li> <div class="comment"> <table class="comment-table" commentId="809204" commentParentId="809116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809204" href="?#comment-809204" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809116" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809204" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809204"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/92199#comment-809178">here</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809204 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809204 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809204"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809122" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809122" href="?#comment-809122" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809122" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809122"> <div class="moveup"> <div class="ttypography"><p>Beautiful Problems. Amazing Round!!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-809122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809122"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809156" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dummybawa" style="position: relative;"> <img src='https://userpic.codeforces.org/1704408/avatar/1522f670cd21321.jpg'/> </a> <div><a href="/profile/dummybawa" title="Expert dummybawa" class="rated-user user-blue">dummybawa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809156" href="?#comment-809156" style="font-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="809156" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809156" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1704408" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809156"> <div class="moveup"> <div class="ttypography"><p>UPD: It's wrong. </p></div> </div> </div> <div class="reply info"> <a class="comment-809156 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809156 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809156"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809178" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809178" href="?#comment-809178" style="font-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="809178" 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="809178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809178"> <div class="moveup"> <div class="ttypography"><p>For DIV 2C/1A can anyone explain with this test case N = 6 and D = 0 1 2 3 2 3. What are the edges that we can have with their weights?</p></div> </div> </div> <div class="reply info"> <a class="comment-809178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809178"> <li> <div class="comment"> <table class="comment-table" commentId="809198" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Zemrith" style="position: relative;"> <img src='https://userpic.codeforces.org/1159882/avatar/2a6566e372882267.jpg'/> </a> <div><a href="/profile/Zemrith" title="Expert Zemrith" class="rated-user user-blue">Zemrith</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809198" href="?#comment-809198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-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="809198" 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="809198" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159882" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809198"> <div class="moveup"> <div class="ttypography"><p>Hello! The answer would be -18.</p><p>Diagram: <img alt=" " src="/predownloaded/8c/88/8c88a0230dea9f499896ee59def659611c605976.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Notice that once you sort the distances, the adjacent nodes have no effect on your final answer. But you can add negative edges as long as they are not adjacent, resulting in such a diagram. Hence you can use prefix sums to solve the problem. (if x nodes came before this, for each node, the answer to add is (x-1)*curr value — csum of first (x-1) nodes). </p><p>Hope that made sense!</p></div> </div> </div> <div class="reply info"> <a class="comment-809198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809198"> <li> <div class="comment"> <table class="comment-table" commentId="809218" commentParentId="809198"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:27">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809218" href="?#comment-809218" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809218" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809218"> <div class="moveup"> <div class="ttypography"><p>Thank you <a class="rated-user user-cyan" href="/profile/Zemrith" title="Специалист Zemrith">Zemrith</a> for so much detail explanation and the solution too it helped me a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-809218 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809218 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809218"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809199" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809199" href="?#comment-809199" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809199" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809199"> <div class="moveup"> <div class="ttypography"><p>first sort the array they will from non negative weight edges. 0 -&gt; 1 -&gt; 2 -&gt; 2 -&gt; 3 -&gt; 3 so the non negative weights will be 1 | 1 | 0 | 1 | 0. form here greedily build most negative weights(backward edges) such that there are no negative cycles.</p></div> </div> </div> <div class="reply info"> <a class="comment-809199 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809199 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809199"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809203" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809203" href="?#comment-809203" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809203" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809203"> <div class="moveup"> <div class="ttypography"><p>First you can sort D and get: <code> N = 6, D = [0, 1, 2, 2, 3, 3] </code></p><p>Now calculate the diffs:</p><p><code>diffs = [1, 1, 0, 1, 0]</code></p><p>The edges for this graph could be something like this:</p> <pre><code> 1 1 0 1 0 &lt;- forward edges 1 &lt;-&gt; 2 &lt;-&gt; 3 &lt;-&gt; 4 &lt;-&gt; 5 &lt;-&gt; 6 -1 -1 0 -1 0 &lt;- backward edges </code></pre><p>Now you have to add more negatives edges, and you could do this by choosing some <code>i</code> and <code>j</code>, <code>i &lt; j</code> and add an edges from <code>j</code> to <code>i</code>, and the weight will be sum of the values from <code>diff[i]</code> to <code>diff[j]</code>.</p><p>Another way to think about this is: look at <code>D</code> array, it represents distances between adjacent nodes, all we have to do is add all of the edges with length 2, then all of the edges of length 3, ..., all of the edges of length <code>N - 1</code>.</p><p>So, for our case we would have these edges</p> <pre><code>a b W ------- 1 2 - 1 2 3 - 1 3 4 - 0 &lt;- adjacent forward edges 4 5 - 1 5 6 - 0 2 1 - -1 3 2 - -1 4 3 - 0 &lt;- adjacent backward edges 5 4 - -1 6 5 - 0 3 1 - -2 4 2 - -1 5 3 - -1 &lt;- edges of length 2 6 4 - -1 4 1 - -2 5 2 - -2 &lt;- edges of length 3 6 3 - -1 5 1 - -3 6 2 - -2 &lt;- edges of length 4 6 1 - -3 &lt;- edges of length 5 </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809203 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809203 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809203"> <li> <div class="comment"> <table class="comment-table" commentId="809221" commentParentId="809203"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809221" href="?#comment-809221" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809203" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809221" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809221"> <div class="moveup"> <div class="ttypography"><p>Thank You <a class="rated-user user-green" href="/profile/ilidar" title="Ученик ilidar">ilidar</a> for clearing my doubt and for detailed explaination.</p></div> </div> </div> <div class="reply info"> <a class="comment-809221 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809221 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809221"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809280" href="?#comment-809280" style="font-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="809280" revisionCount="7" revision="7"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">7</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809280" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+18</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809280"> <div class="moveup"> <div class="ttypography"><p>Could someone please provide a more strict intuition or insight of Div2D/Div1B of why &quot;the actual probability p does not matter&quot;? The intuition in the editorial is still alien to me of why those choices of not progess toward to either stacks (and probability 'p' also changes from time to time too) doesn't matter.</p><p>Update: Here is the intuition I came up with (The strict proof can be found in the comment of the author below)</p><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left) in some states of the current tree.</p><p>now, we will try break this $$$dp_{i,j}$$$ down into the sum of $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$</p><p>We will try to illustrate this with trying to split and color, either red or blue, a stick of length $$$1$$$. The length of the sticks representing the 'probability', and the color of the sticks will represent $$$dp_{i-1,j}$$$(red) or $$$dp_{i,j-1}$$$(blue), depending on the color.</p><p>Suppose in the current state, we have probability $$$p$$$ for choosing to pop each stacks, and the rest $$$1-2p$$$ of doing nothing. The picture will look like this:</p><p><a href="https://ibb.co/q9HjQTm"><img alt="Tree-Array-Rep" border="0" src="/predownloaded/13/57/135732d2b0967af0f76c1dba28df72086f234c7d.png" style="max-width: 100.0%;max-height: 100.0%;" /></a></p><p>We will split the stick equally(*) into several sticks of length $$$p$$$, and then color two of them red and blue. (* We can split it evenly because in the original problem, $$$p$$$ is in the form $$$\frac{1}{number\ of\ candidate\ unmark\ nodes}$$$ ) Now, the remaining sticks represent the state of $$$dp_{i,j}$$$ again (in some other state of the entire tree, so might be in some different $$$p$$$). That means we will split those sticks similary.</p><p>The key observations is:</p><p>1) We know that, in the original problem, if we keep picking nodes that aren't progressing toward the target nodes, we will run out of nodes eventually and finally choose the two nodes. That means, all the sticks will eventually colored into 'red' and 'blue'.</p><p>2) When we split a stick into several smaller equal length sticks, we will color two of them into red and blue. <strong>Those two sticks always have the same length</strong>. That means, the total length of blue sticks and the total length of red sticks will be equal in the end.</p><p>Analogically, that means, eventually, $$$dp_{i,j}$$$ will split into $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$ evenly, no matter $$$p$$$ might be or the state of tree of $$$dp_{i,j}$$$ might be. Therefore, $$$dp_{i,j} = \frac{1}{2} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-809280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809280"> <li> <div class="comment"> <table class="comment-table" commentId="809284" commentParentId="809280"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809284" href="?#comment-809284" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809280" style="font-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="809284" 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="809284" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809284"> <div class="moveup"> <div class="ttypography"><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left), with having arbitary probability $$$0 &lt; p \leq 0.5$$$ of chosing to pick the top of each stack (and $$$1-2p$$$ for doing nothing). Then</p><p>$$$dp_{i,j}=\int_{0}^{0.5} x \cdot (dp_{i-1,j}+dp_{i,j-1}) + (1-2x) \cdot dp_{i,j} \,dx$$$</p><p>Solving the equation, we get $$$dp_{i,j}=\frac{1}{6} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$ What is the mistake in this logic?</p></div> </div> </div> <div class="reply info"> <a class="comment-809284 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809284 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809284"> <li> <div class="comment"> <table class="comment-table" commentId="809399" commentParentId="809284"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809399" href="?#comment-809399" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809284" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809399" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809399"> <div class="moveup"> <div class="ttypography"><p>The biggest issue with this logic is that it's assuming $$$p$$$ is arbitrary chosen from a certain state. While $$$p$$$ can be anything in the world, it is always an exact number from a certain state, hence why an integral is wrong. </p><p>As a different type of intuition, you can think, &quot;is it more likely to reach $$$(i-1, j)$$$ than state $$$(i, j-1)$$$&quot;? and vice versa. For me at least, I don't see how it's possible for either of those questions to be true, so they should be equal.</p><p>If you're looking for a more rigorously correct $$$dp$$$, it would look something like this.</p> <div class="spoiler"><b class="spoiler-title">Proof</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp_{i, j, S}$$$ denote the probability of reaching some node $$$i$$$ distance away before some node $$$j$$$ distance away where $$$S$$$ is a representation of the entire state of of the process (not necessarily an integer). I think you already understood why we can assume the $$$lca$$$ is already reached. We aim to show that $$$S$$$ does not matter in our calculation. Assume inductively that $$$S$$$ does not matter. So, we can assume that states $$$(i-1, j)$$$ and states $$$(i, j-1)$$$ are irrelevant to $$$S$$$. Hence, the part we need to care about is $$$(1-2p) dp_{i, j, S \rightarrow S_a}$$$. A way of thinking about this part of the transition is moving through the collection of $$$S$$$ with the state $$$(i, j)$$$. Obviously, the $$$dp$$$ is a $$$DAG$$$ because no state $$$S$$$ can reach another. Each bounce takes a certain probability $$$p$$$ which is just multiplied in the current path. So, for each state $$$S$$$ with state $$$(i, j)$$$, we have a certain probability to reach it by simply calculating $$$dp$$$ along a DAG as is traditional. Then, from those states of $$$(i, j)$$$ you transition to $$$(i, j-1)$$$ with an equal probability $$$(i-1, j)$$$. So, they have to be equal. Finally, this argument holds for any initial state $$$S$$$ that you reach, so we can conclude that, from any state $$$S$$$ with a state of $$$(i, j)$$$, the probability of transitions to $$$(i-1, j)$$$ and $$$(i, j-1)$$$ are always exactly $$$0.5$$$.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-809399 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809399 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809399"> <li> <div class="comment"> <table class="comment-table" commentId="809701" commentParentId="809399"> <tr> <td class="left"> <div style="position: absolute; left: 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/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809701" href="?#comment-809701" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809399" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809701" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809701"> <div class="moveup"> <div class="ttypography"><p>I see, thank you so much!</p></div> </div> </div> <div class="reply info"> <a class="comment-809701 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809701 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809701"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809298" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/satyam_singh93" style="position: relative;"> <img src='https://userpic.codeforces.org/1763011/avatar/9d9fa405de19ab0e.jpg'/> </a> <div><a href="/profile/satyam_singh93" title="Newbie satyam_singh93" class="rated-user user-gray">satyam_singh93</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809298" href="?#comment-809298" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809298" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1763011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809298"> <div class="moveup"> <div class="ttypography"><p>I am getting wrong ans . could someone tell me where the code make differene ( [yestrday competiton problem .</p><p>`](<a href="https://codeforces.com/contest/1541/problem/B)">https://codeforces.com/contest/1541/problem/B)</a>.</p> <pre><code>int main( ) { clock_t begin = clock(); file_i_o(); // Write your code here.... int t; cin&gt;&gt;t; while(t-- ){ int n; cin&gt;&gt;n; vector&lt;pair&lt;int,int&gt;&gt;v; v.push_back({0,0}); loop(i,0,n) { int x; cin&gt;&gt;x; v.pb({x,i+1}); } sort(v.begin()+1,v.end()); int count =0; for(int i=1 ; i&lt;=n;i++) { for(ll j=i+1;j&lt;=n;j++) { ll left = v[i].first * v[j].first; ll right = v[i].second + v[j].second; if(left == right) count++; if(left &gt; 2*n ) break; } } cout&lt;&lt;count&lt;&lt;endl; } </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809298 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809298 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809298"> <li> <div class="comment"> <table class="comment-table" commentId="809305" commentParentId="809298"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809305" href="?#comment-809305" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809298" style="font-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="809305" 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="809305" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809305"> <div class="moveup"> <div class="ttypography"><p>v[i].first * v[j].first can create overflow. So, you need to convert them to long long by using</p><p>ll left = 1LL * v[i].first * v[j].first;</p><p>instead and it would pass.</p><p>(Simply save the value in long long won't help. You need to convert them to long long before doing multiplication. 1LL* is one way)</p></div> </div> </div> <div class="reply info"> <a class="comment-809305 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809305 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809305"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809309" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809309" href="?#comment-809309" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809309" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809309"> <div class="moveup"> <div class="ttypography"><p>Hi, in problem Div1.B/Div2.D; I can't wrap my head around $$$F[x][y]=F[x−1][y]/2+F[x][y−1]/2$$$. Why is it not $$$F[x][y]=F[x−1][y+1]/2+F[x+1][y−1]/2$$$, can someone please explain to me why is my transition wrong and/or why is the aforementioned transition correct? </p></div> </div> </div> <div class="reply info"> <a class="comment-809309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809309"> <li> <div class="comment"> <table class="comment-table" commentId="809311" commentParentId="809309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809311" href="?#comment-809311" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809311" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809311"> <div class="moveup"> <div class="ttypography"><p>x and y is the distance left for each side right? So, if you take one out, it won't make sense to add that one to the other side since the distance should be either x-1 and y or x and y-1.</p></div> </div> </div> <div class="reply info"> <a class="comment-809311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809311"> <li> <div class="comment"> <table class="comment-table" commentId="809339" commentParentId="809311"> <tr> <td class="left"> <div style="position: absolute; left: 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/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809339" href="?#comment-809339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809339" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809339"> <div class="moveup"> <div class="ttypography"><p>Thank you so much I understand. I had a minor misunderstanding of the parameters to the dp state.</p></div> </div> </div> <div class="reply info"> <a class="comment-809339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809339"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809371" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:13">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809371" href="?#comment-809371" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809371" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809371"> <div class="moveup"> <div class="ttypography"><p>PLease explain why 2 same codes are not giving the same ans</p><p>code forces round 728 div2<br />Problem B :<a href="https://codeforces.com/contest/1541/problem/B">https://codeforces.com/contest/1541/problem/B</a></p><p>AC Submission : <a href="https://ide.codingblocks.com/s/579769">https://ide.codingblocks.com/s/579769</a></p><p>Wrong output Submission :<a href="https://ide.codingblocks.com/s/579771">https://ide.codingblocks.com/s/579771</a></p><p>Difference is using of macro (node) instead of pair&lt;int,int&gt; </p><p>Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-809371 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809371 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809371"> <li> <div class="comment"> <table class="comment-table" commentId="809379" commentParentId="809371"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809379" href="?#comment-809379" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809371" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809379" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809379"> <div class="moveup"> <div class="ttypography"><p>If i am using #define node pair&lt;int,int&gt; it is getting accepted but when i am using typedef pair&lt;int,int&gt; node; it is giving wrong answer</p><p>Why this is happening ?? Is it a bug??</p></div> </div> </div> <div class="reply info"> <a class="comment-809379 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809379 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809379"> <li> <div class="comment"> <table class="comment-table" commentId="809407" commentParentId="809379"> <tr> <td class="left"> <div style="position: absolute; left: 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/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 19:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809407" href="?#comment-809407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809379" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809407" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809407"> <div class="moveup"> <div class="ttypography"><p>Not really sure why this is happening.</p><p>However, I think the problem is the position of #define int long long. So, for #define pair&lt;int,int&gt; node it seems that compiler change node -&gt; pair&lt;int,int&gt; -&gt; pair&lt;long long, long long&gt;. However, when you do typedef, it still keeps in pair&lt;int, int&gt; which creates an overflow problem later on. </p><p>I did try moving #define int long long up above typedef and the code pass. So, my best guess is #define int long long only replace int after that position with long long. Thus, node is still pair&lt;int, int&gt; in the typedef solution, while node is changed to pair&lt;long long, long long&gt; in the second solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-809407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809407"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809627" href="?#comment-809627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809627"> <div class="moveup"> <div class="ttypography"><p>May I ask why in the Div1D solution ci=i-bi, I think it should be ci=bi ...</p></div> </div> </div> <div class="reply info"> <a class="comment-809627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809627"> <li> <div class="comment"> <table class="comment-table" commentId="809631" commentParentId="809627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809631" href="?#comment-809631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809631" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809631"> <div class="moveup"> <div class="ttypography"><p>Check the definition of bi again dude. bi here means <strong>number of elements greater than pi</strong>. So to get ci, which is <strong>number of elements smaller than pi</strong>, you need i-bi.</p></div> </div> </div> <div class="reply info"> <a class="comment-809631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809631"> <li> <div class="comment"> <table class="comment-table" commentId="809636" commentParentId="809631"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809636" href="?#comment-809636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809636"> <div class="moveup"> <div class="ttypography"><p>I read it again. If I read it correctly, bi stands for j&lt;i,pj&gt;pi, and ci stands for j&gt;i,pj&lt;pi. For example, p={1,3,5,4,6,2}, I think b4=1,c4=1, please point out my problem</p></div> </div> </div> <div class="reply info"> <a class="comment-809636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809636"> <li> <div class="comment"> <table class="comment-table" commentId="809638" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809638" href="?#comment-809638" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809638" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809638"> <div class="moveup"> <div class="ttypography"><p>oh, the array index starts from 1</p></div> </div> </div> <div class="reply info"> <a class="comment-809638 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809638 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809638"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809639" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809639" href="?#comment-809639" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809639" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809639"> <div class="moveup"> <div class="ttypography"><p>You are right.</p><p>I guess it might just be typo and ci stands for j&lt;i, pj&lt;pi. At least with this definition of ci the algorithm seems correct :)</p></div> </div> </div> <div class="reply info"> <a class="comment-809639 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809639 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809639"> <li> <div class="comment"> <table class="comment-table" commentId="809641" commentParentId="809639"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809641" href="?#comment-809641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809639" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809641"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-809641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809641"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809705" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/darthrevenge" style="position: relative;"> <img src='https://userpic.codeforces.org/1567000/avatar/ee31d2a91a9575b9.jpg'/> </a> <div><a href="/profile/darthrevenge" title="Candidate Master darthrevenge" class="rated-user user-violet">darthrevenge</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809705" href="?#comment-809705" style="font-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="809705" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809705" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1567000" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809705"> <div class="moveup"> <div class="ttypography"><p>Here's my solution of B div 1 / D div 2 without LCA, using single DFS per node. <a href="/contest/1540/submission/120700765" title="Посылка 120700765 от darthrevenge">120700765</a> It is similar to what <a class="rated-user user-violet" href="/profile/OleschY" title="Кандидат в мастера OleschY">OleschY</a> suggested above. I've tried to describe it in the <a href="https://codeforces.com/blog/entry/92284">blog</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-809705 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809705 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809705"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809951" href="?#comment-809951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809951"> <div class="moveup"> <div class="ttypography"><p>Can someone explain how you can find the LCA for each pair so quick? Iterating through every root is and then considering every pair is already N^3</p></div> </div> </div> <div class="reply info"> <a class="comment-809951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809951"> <li> <div class="comment"> <table class="comment-table" commentId="809965" commentParentId="809951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PurpleCrayon" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809965" href="?#comment-809965" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809965" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="1604355" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809965"> <div class="moveup"> <div class="ttypography"><p>There are a couple ways you could do it:</p> <ol> <li>Just use standard binary lifting (initialize once for each root). This runs in $$$\mathcal{O}(n^3 \log{}n)$$$, and should pass under the given constraints. You could also just use $$$\mathcal{O}(1)$$$ lca using an rmq over an euler tour.</li> <li>You could use a version of dp, where $$$dp[a][b] = lca(a, b)$$$. If the depth of $$$a$$$ is greater than the depth of $$$b$$$, $$$dp[a][b] = dp[parent[a]][b]$$$, otherwise $$$dp[a][b] = dp[a][parent[b]]$$$. The base cases are $$$dp[a][a] = a$$$ for all $$$a$$$. This runs in $$$\mathcal{O}(n^3)$$$.</li> <li>You could extend this idea and do the main solution's dp directly on the tree (without ever worrying about lca's). The recurrence is equivalent to the main solution ($$$dp[a][b] = \frac{dp[parent[a]][b]+dp[a][parent[b]]}{2}$$$ with the base cases being one node is an ancestor of the other.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-809965 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809965 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809965"> <li> <div class="comment"> <table class="comment-table" commentId="809967" commentParentId="809965"> <tr> <td class="left"> <div style="position: absolute; left: 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/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809967" href="?#comment-809967" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809965" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809967" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809967"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the detailed answer!</p></div> </div> </div> <div class="reply info"> <a class="comment-809967 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809967 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809967"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="810320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Anurag_20" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Anurag_20" title="Specialist Anurag_20" class="rated-user user-cyan">Anurag_20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/30/2021 19:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810320" href="?#comment-810320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810320" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1600346" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810320"> <div class="moveup"> <div class="ttypography"><p>O(n2) is also working for div2 C Great Graphs. <a href="https://codeforces.com/contest/1540/submission/120964787">https://codeforces.com/contest/1540/submission/120964787</a></p></div> </div> </div> <div class="reply info"> <a class="comment-810320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810320"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="813828" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/T404" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/T404" title="Master T404" class="rated-user user-orange">T404</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/09/2021 19:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-813828" href="?#comment-813828" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="813828" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="523287" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-813828"> <div class="moveup"> <div class="ttypography"><p>Div1D can be done in $$$O(n \sqrt{n})$$$. We can use square root decomposition to replace all BITs in tutorial. Since a value in a non-updated position changes by at most one and all values change in the same direction, the full recomputation is only needed in the updated position and we can perform an incremental change in $$$O(1)$$$ for values in each non-updated positions.</p><p><a href="https://codeforces.com/contest/1540/submission/121831547">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-813828 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-813828 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-813828"> <li> <div class="comment"> <table class="comment-table" commentId="834051" commentParentId="813828"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KeyID" style="position: relative;"> <img src='https://userpic.codeforces.org/226684/avatar/10e3671716bf6859.jpg'/> </a> <div><a href="/profile/KeyID" title="Grandmaster KeyID" class="rated-user user-red">KeyID</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/29/2021 12:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-834051" href="?#comment-834051" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-813828" style="font-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="834051" 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="834051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="226684" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-834051"> <div class="moveup"> <div class="ttypography"><p>Realy impressive solution. I'm surprised no stars were given to you until me. Maybe many people didn't get your idea since the solution is actually much more complicated than your brief comment(at least in my opinion). I also wrote a piece of code which used your method but simplified a small part of steps. <a href="https://codeforces.com/contest/1540/submission/127317031">Here</a> it is.</p></div> </div> </div> <div class="reply info"> <a class="comment-834051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-834051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-834051"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="837924" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Harolinch" style="position: relative;"> <img src='https://userpic.codeforces.org/427341/avatar/cf8608aeb55edc95.jpg'/> </a> <div><a href="/profile/Harolinch" title="Pupil Harolinch" class="rated-user user-green">Harolinch</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837924" href="?#comment-837924" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837924" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="427341" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837924"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a> in problem Tree array you said that Fixing a given root r, the expected value of the entire process is obviously the sum of the expected values for a fixed root divided by n.</p><p>why we divide by n at the end ? </p></div> </div> </div> <div class="reply info"> <a class="comment-837924 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837924 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837924"> <li> <div class="comment"> <table class="comment-table" commentId="837928" commentParentId="837924"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837928" href="?#comment-837928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-837924" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837928" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837928"> <div class="moveup"> <div class="ttypography"><p>The calculation is independent based on whichever node that you choose first (it becomes the “root”). Initially you choose one of $$$n$$$ nodes with equal probability so you divide by $$$n$$$ at the end after you’ve summed up the independent expected value after choosing the node $$$i$$$ initially.</p></div> </div> </div> <div class="reply info"> <a class="comment-837928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837928"> </ul> </div> </li> </ul> </div> <br/> <div id="editBox-100805" 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 firstPreview100805 = true; var lastPreviewContent100805 = ''; 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=100805] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=100805] 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-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, 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:33:28</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:'81289372dffb0c4e',t:'MTY5NjcwNzIwOC45MzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1541A
1541
A
ru
A. Симпатичные перестановки
<div class="problem-statement"><div class="header"><div class="title">A. Симпатичные перестановки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Есть ряд из $$$n$$$ кошек, пронумерованных с $$$1$$$ по $$$n$$$: $$$i$$$-я кошка на позиции $$$i$$$. Кошкам надоедает вращаться на одном и том же месте целый день, поэтому они хотят поменяться местами так, чтобы никакая кошка не осталась на том же самом месте. Кошки очень ленивы, а поэтому они хотят минимизировать суммарное расстояние, на которое им нужно передвинуться. Помогите им решить, какой кошке переместиться на какое место.</p><p>Например, если кошки $$$3$$$, то можно выбрать следующую перестановку: $$$[3, 1, 2]$$$. Никакая кошка не осталась на своем месте. Суммарное расстояние, на которое сдвинулись кошки равно $$$1 + 1 + 2 = 4$$$, т. е. кошка $$$1$$$ сдвинулась на один вправо, кошка $$$2$$$ сдвинулась на один вправо, а кошка $$$3$$$ — на два влево.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой и единственной строке каждого набора задано одно целое число $$$n$$$ ($$$2 \leq n \leq 100$$$) — количество кошек.</p><p>Можно доказать, что при текущих ограничениях ответ всегда существует.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов — по одному на набор входных данных. Каждый ответ должен состоять из $$$n$$$ целых чисел — перестановки минимальной стоимости. Если существует несколько ответов, выведите любой из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 3 1 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных есть одна возможная перестановка, удовлетворяющая условиям: $$$[2, 1]$$$.</p><p>Второй набор описан в условии задачи. Другой возможный ответ — это $$$[2, 3, 1]$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="fc7e19b8f5592d71aedd2996523d63b3"/> <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="3a2e30eec6604291efb1f3ef212d19e2d7715bd7"/> <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='fc7e19b8f5592d71aedd2996523d63b3'>&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%2F1541%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='fc7e19b8f5592d71aedd2996523d63b3'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1541">Codeforces Round 728 (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='fc7e19b8f5592d71aedd2996523d63b3'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1541/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='fc7e19b8f5592d71aedd2996523d63b3'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1027092"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='fc7e19b8f5592d71aedd2996523d63b3'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1027092"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92093" title="Codeforces Round #728" target="_blank">Codeforces Round #728 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13929" resourceName="Codeforces Round #728" resourceManual="true" src="//codeforces.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/92199" title="Tutorial" target="_blank">Tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13941" 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/1541">Задачи</a></li> <li><a href="/contest/1541/submit">Отослать</a></li> <li><a href="/contest/1541/my">Мои посылки</a></li> <li><a href="/contest/1541/status">Статус</a></li> <li><a href="/contest/1541/hacks">Взломы</a></li> <li><a href="/contest/1541/room/1">Комната</a></li> <li><a href="/contest/1541/standings">Положение</a></li> <li><a href="/contest/1541/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_a8e06168eff8450b9039ee0f679c9bb50ee00bc3"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Симпатичные перестановки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Есть ряд из $$$n$$$ кошек, пронумерованных с $$$1$$$ по $$$n$$$: $$$i$$$-я кошка на позиции $$$i$$$. Кошкам надоедает вращаться на одном и том же месте целый день, поэтому они хотят поменяться местами так, чтобы никакая кошка не осталась на том же самом месте. Кошки очень ленивы, а поэтому они хотят минимизировать суммарное расстояние, на которое им нужно передвинуться. Помогите им решить, какой кошке переместиться на какое место.</p><p>Например, если кошки $$$3$$$, то можно выбрать следующую перестановку: $$$[3, 1, 2]$$$. Никакая кошка не осталась на своем месте. Суммарное расстояние, на которое сдвинулись кошки равно $$$1 + 1 + 2 = 4$$$, т. е. кошка $$$1$$$ сдвинулась на один вправо, кошка $$$2$$$ сдвинулась на один вправо, а кошка $$$3$$$ — на два влево.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой и единственной строке каждого набора задано одно целое число $$$n$$$ ($$$2 \leq n \leq 100$$$) — количество кошек.</p><p>Можно доказать, что при текущих ограничениях ответ всегда существует.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов — по одному на набор входных данных. Каждый ответ должен состоять из $$$n$$$ целых чисел — перестановки минимальной стоимости. Если существует несколько ответов, выведите любой из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 3 1 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных есть одна возможная перестановка, удовлетворяющая условиям: $$$[2, 1]$$$.</p><p>Второй набор описан в условии задачи. Другой возможный ответ — это $$$[2, 3, 1]$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c6f2ce659d63',t:'MTY5NjY2NzM3NC43MTAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*800"]
https://codeforces.com/blog/entry/92199
<!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="ea33d124a1ff874ace73f937748d303e"/> <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="Codeforces Round #728 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #728 Editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='ea33d124a1ff874ace73f937748d303e'>&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%2F92199">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='ea33d124a1ff874ace73f937748d303e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:31:32</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:31:32</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='ea33d124a1ff874ace73f937748d303e'/> <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/PurpleCrayon">PurpleCrayon</a></li> <li class="current selectedLava"><a href="/blog/PurpleCrayon">Blog</a></li> <li><a href="/teams/with/PurpleCrayon">Teams</a></li> <li><a href="/submissions/PurpleCrayon">Submissions</a></li> <li><a href="/groups/with/PurpleCrayon">Groups</a></li> <li><a href="/contests/with/PurpleCrayon">Contests</a></li> <li><a href="/contests/writer/PurpleCrayon">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/PurpleCrayon" style="text-decoration:none;color:black !important;">PurpleCrayon's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="92809"> <div class="title"> <a href="/blog/entry/92199"> <p>Codeforces Round #728 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a>, <a href="/topic/92809/en10">history</a>, <span class="format-humantime" title="Jun/25/2021 20:44">2 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><a href="/contest/1541/problem/A" title="Codeforces Round 728 (Div. 2)">1541A - Pretty Permutations</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The parity (whether $$$n$$$ is odd or even) matters.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Swapping two adjacent cats keeps both of them close to their original location and changes both of their locations.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>If $$$n$$$ is even, the optimal distance is $$$n$$$, and if $$$n$$$ is odd the optimal distance is $$$n+1$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541A">Tutorial is loading...</div></div></div><p><a href="/contest/1541/problem/B" title="Codeforces Round 728 (Div. 2)">1541B - Pleasant Pairs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>$$$i+j \leq 2 \cdot n$$$</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The number of pairs $$$(a, b)$$$ such that $$$a \cdot b \leq x$$$ is $$$O(x log x)$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/A" title="Codeforces Round 728 (Div. 1)">1540A - Great Graphs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What's the minimum value that an edge from $$$a$$$ to $$$b$$$ can be?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use edges with negative value whenever you can.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The sum of the values of edges with positive weight must be $$$\geq$$$ the maximum value in the array.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540A">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Tree Array</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Fix the initial node chosen and root the tree there, what is the contribution of each pair of nodes?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Nothing matters besides the path from node $$$a$$$ to node $$$b$$$, and the initially chosen node $$$r$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>You are given two stacks of size $$$a_1$$$ and $$$a_2$$$. In a single step, you randomly choose a stack to remove a single item from. What is the probability that $$$a_1$$$ becomes $$$0$$$ before $$$a_2$$$? Can you extend this argument for an arbitrary probability $$$p$$$ to remove from one of the two stacks, and a probability of $$$1-2p$$$ to do nothing?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/C2" title="Codeforces Round 728 (Div. 1)">1540C2 - Converging Array (Hard Version)</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What are the invariants? The monovariants?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What is the prefix sum array of the converged array? What is the difference array of the converged array?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you conducted the process on a prefix of size $$$1$$$, then of size $$$2$$$, and on and on?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How many values $$$x$$$ are actually interesting?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540C2">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Inverse Inversions</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The answer is always unique.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Try to figure out what the location of the $$$i$$$-th element would be if you only looked at the first $$$i$$$ elements, then the first $$$i+1$$$, etc. to find an $$$O(nq)$$$ solution.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use sqrt decomposition to optimize it.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540D">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/E" title="Codeforces Round 728 (Div. 1)">1540E - Tasty Dishes</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How much does each chef's initial dish contribute at time $$$k$$$?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you really, really wanted to use matrix exponentiation?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How can you multiply some vectors by a matrix in $$$O(N)$$$ time? (go back to linear algebra class)</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Decompose into linear combinations of eigenvectors.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540E">Tutorial is loading...</div></div></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/1540" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 1)</a> </span> </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/1541" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-191295-92809").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "191295", blogEntryId: "92199", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-92809"><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'>+96</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-92809"><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/PurpleCrayon"><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/PurpleCrayon"> PurpleCrayon </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="Jun/25/2021 20:44">2 years ago</span> </li> <li> <a href="/blog/entry/92199#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/92199#comments"> 170 </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="100805"> <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 (136)</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="808750" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808750" href="?#comment-808750" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808750" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-66" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-66</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808750"> <div class="moveup"> <div class="ttypography"><p>PURPLECRAYON ORZ</p></div> </div> </div> <div class="reply info"> <a class="comment-808750 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808750 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808750"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808751" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hbarp" style="position: relative;"> <img src='https://userpic.codeforces.org/1387715/avatar/c727a810db6ffb66.jpg'/> </a> <div><a href="/profile/hbarp" title="Candidate Master hbarp" class="rated-user user-violet">hbarp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808751" href="?#comment-808751" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808751" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="1387715" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-83</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808751"> <div class="moveup"> <div class="ttypography"><p>Damn, so orz round. <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Мастер PurpleCrayon">PurpleCrayon</a> orz</p></div> </div> </div> <div class="reply info"> <a class="comment-808751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808751"> <li> <div class="comment"> <table class="comment-table" commentId="808805" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/naman1601" style="position: relative;"> <img src='https://userpic.codeforces.org/1703219/avatar/d63fc523dc05fda8.jpg'/> </a> <div><a href="/profile/naman1601" title="Master naman1601" class="rated-user user-orange">naman1601</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808805" href="?#comment-808805" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808805" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-51" data-commentUserId="1703219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-51</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808805"> <div class="moveup"> <div class="ttypography"><p>yeah, amazing problemset, not speedforces at all :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808805 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808805 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808805"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808817" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LOVELY_BOY_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/LOVELY_BOY_" title="Newbie LOVELY_BOY_" class="rated-user user-gray">LOVELY_BOY_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808817" href="?#comment-808817" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-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="808817" 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="808817" class="CommentVoteFrame" data-commentRating="35" data-commentUserId="2089809" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808817"> <div class="moveup"> <div class="ttypography"><p>LOL <a class="rated-user user-blue" href="/profile/hbarp" title="Эксперт hbarp">hbarp</a>,even you didn't participate in the contest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808817 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808817 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808817"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808753" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DontLookBack" style="position: relative;"> <img src='https://userpic.codeforces.org/1534766/avatar/4eacdc5f9758fc28.jpg'/> </a> <div><a href="/profile/DontLookBack" title="Specialist DontLookBack" class="rated-user user-cyan">DontLookBack</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808753" href="?#comment-808753" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808753" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1534766" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808753"> <div class="moveup"> <div class="ttypography"><p>I am curious, how many div2 testers solved D?</p></div> </div> </div> <div class="reply info"> <a class="comment-808753 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808753 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808753"> <li> <div class="comment"> <table class="comment-table" commentId="808826" commentParentId="808753"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/highonjuice" style="position: relative;"> <img src='https://userpic.codeforces.org/1457566/avatar/f7988dd2af03d38b.jpg'/> </a> <div><a href="/profile/highonjuice" title="Pupil highonjuice" class="rated-user user-green">highonjuice</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808826" href="?#comment-808826" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808753" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808826" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1457566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808826"> <div class="moveup"> <div class="ttypography"><p>like 2 ppl, it was hard for me</p></div> </div> </div> <div class="reply info"> <a class="comment-808826 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808826 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808826"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808757" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tlatoani" style="position: relative;"> <img src='https://userpic.codeforces.org/614001/avatar/598b4e8358aad1b4.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/Tlatoani" title="Grandmaster Tlatoani" class="rated-user user-red">Tlatoani</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:18">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808757" href="?#comment-808757" style="font-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="808757" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="808757" class="CommentVoteFrame" data-commentRating="121" data-commentUserId="614001" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+121</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808757"> <div class="moveup"> <div class="ttypography"><h4>Alternate solution to <a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Инвертируем инверсии</a></h4><p>(Read the first nontrivial paragraph of the editorial before reading this alternate solution)</p><p>Let $$$p_r(k) = x$$$ denote that of the numbers $$$p(1), \ldots, p(r)$$$ in sorted order, $$$p(k)$$$ is equal to the $$$x$$$th of these numbers. We will take a decomposition strategy just as the editorial does, though our strategy will be different. We will divide $$$[1, n]$$$ into blocks of length $$$b$$$. For each block covering some interval $$$[l, r]$$$, we will store $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>This means that for any $$$k$$$, if we know $$$p_r(k)$$$ for some block $$$[l, r]$$$, then we can determine $$$p_{r'}(k)$$$ for the block $$$[l', r']$$$ immediately to the right by binary searching on the numbers stored for $$$[l', r']$$$. Therefore, we can perform queries in $$$O\left(\frac n b \lg b\right)$$$.</p><p>We now need to figure out updates. There are probably simple ways to perform updates in $$$O(b\lg b)$$$, but this yields an overall runtime of $$$O(q\sqrt n \lg n)$$$ which is too slow.</p><p>Therefore, we can instead store each block as a segment tree. For each range $$$[l, r]$$$ in the segment tree we store the same thing we store for the whole block: $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>We then have to quickly merge two intervals. We can merge two intervals of length $$$\lambda$$$ in $$$O(\lambda \lg \lambda)$$$ by doing binary search just as we did above, but this still only yields $$$O(b\lg b)$$$ update overall. However, these $$$\lambda$$$ binary searches can be optimized using two pointers to $$$O(\lambda)$$$, making the overall update $$$O(b)$$$.</p><p>We thus have $$$O\left(\frac n b \lg b\right)$$$ query and $$$O(b)$$$ update. Therefore, we can choose $$$b = \sqrt{n\lg n}$$$ to attain an overall runtime of $$$O\left(q\sqrt{n\lg n}\right)$$$ just as the editorial does.</p><p><a href="https://codeforces.com/contest/1540/submission/120611645">Submission in Kotlin</a></p><p><a href="https://codeforces.com/contest/1540/submission/120612729">Submission in C++</a></p><p>It is interesting to note that this solution is quite fast. At the time of writing this update, the C++ version is the fastest correct submission (and runs under 1 second!) and the Kotlin version is faster than the vast majority of submissions.</p></div> </div> </div> <div class="reply info"> <a class="comment-808757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808757"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808765" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardcode229" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardcode229" title="Newbie hardcode229" class="rated-user user-gray">hardcode229</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808765" href="?#comment-808765" style="font-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="808765" 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="808765" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1635180" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808765"> <div class="moveup"> <div class="ttypography"><p>The 3rd hint for the second problem is same as that of the first problem, is it related or a mistake? <strong>UPD:</strong> it is corrected.</p></div> </div> </div> <div class="reply info"> <a class="comment-808765 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808765 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808765"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808769" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/peanut" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/peanut" title="Specialist peanut" class="rated-user user-cyan">peanut</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:24">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808769" href="?#comment-808769" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808769" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="1167233" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+22</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808769"> <div class="moveup"> <div class="ttypography"><p>speedforces.</p></div> </div> </div> <div class="reply info"> <a class="comment-808769 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808769 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808769"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808781" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/graphs_11" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/graphs_11" title="Specialist graphs_11" class="rated-user user-cyan">graphs_11</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808781" href="?#comment-808781" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808781" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1610110" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808781"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">Problem B Detailed Explanation</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808781 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808781 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808781"> <li> <div class="comment"> <table class="comment-table" commentId="809069" commentParentId="808781"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:40">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809069" href="?#comment-809069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808781" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809069" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809069"> <div class="moveup"> <div class="ttypography"><p>Thank you, very well explained</p></div> </div> </div> <div class="reply info"> <a class="comment-809069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809069"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808790" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PC_E1052" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PC_E1052" title="Pupil PC_E1052" class="rated-user user-green">PC_E1052</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808790" href="?#comment-808790" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808790" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="811219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808790"> <div class="moveup"> <div class="ttypography"><p>c was too easy, d was too hard. but d was very nice problem though. </p></div> </div> </div> <div class="reply info"> <a class="comment-808790 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808790 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808790"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808793" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808793" href="?#comment-808793" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808793" class="CommentVoteFrame" data-commentRating="58" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+58</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808793"> <div class="moveup"> <div class="ttypography"><p>Paging <a class="rated-user user-legendary" href="/profile/ecnerwala" title="Легендарный гроссмейстер ecnerwala"><span class="legendary-user-first-letter">e</span>cnerwala</a> to explain his solution to D1E if he'd like. It seems offline?</p></div> </div> </div> <div class="reply info"> <a class="comment-808793 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808793 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808793"> <li> <div class="comment"> <table class="comment-table" commentId="808979" commentParentId="808793"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ecnerwala" 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/ecnerwala" title="Legendary Grandmaster ecnerwala" class="rated-user user-legendary"><span class="legendary-user-first-letter">e</span>cnerwala</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808979" href="?#comment-808979" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808793" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808979" class="CommentVoteFrame" data-commentRating="40" data-commentUserId="57502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808979"> <div class="moveup"> <div class="ttypography"><p>My solution is $$$O(K N^3 + QN)$$$. I just precomputed the coefficient of each $$$a_i$$$ for each prefix-range for each number of days since person $$$i$$$ becomes positive (only $$$1000$$$ possible days) in $$$O(N \cdot K \cdot N^2)$$$, and then summed up the appropriate ones to answer each query in $$$O(N)$$$. It's written in the offline style to use only $$$O(KN)$$$ memory at a time (grouped by $$$a_i$$$) instead of $$$O(KN^2)$$$.</p><p>My passing submission is just $$$KN^3 / 6$$$ instead of the $$$KN^3$$$ I submitted in contest :'(</p><p>If you guys wanted to prevent this, $$$K$$$ could've been much higher, like $$$1e18$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808979 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808979 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808979"> <li> <div class="comment"> <table class="comment-table" commentId="809002" commentParentId="808979"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809002" href="?#comment-809002" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808979" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809002" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809002"> <div class="moveup"> <div class="ttypography"><p>:( I knew of this solution (it’s why ML is tight) but I didn’t realize that it could be done offline with small memory. Of course $$$K$$$ higher is obvious solution but main issue is that the extra modulos from binary exponentiation make it very hard to pass in Java without allowing other unoptimal solutions through such as precomputing inverses of the matrix. Probably $$$k=10^5$$$ would’ve been a better choice. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-809002 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809002 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809002"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808795" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zukonit14" style="position: relative;"> <img src='https://userpic.codeforces.org/1192187/avatar/5afd49be87fb87d9.jpg'/> </a> <div><a href="/profile/zukonit14" title="Expert zukonit14" class="rated-user user-blue">zukonit14</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808795" href="?#comment-808795" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808795" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1192187" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808795"> <div class="moveup"> <div class="ttypography"><p>Does Div2 D deserved to be D Problem? According to me it should've been Div2 E.</p></div> </div> </div> <div class="reply info"> <a class="comment-808795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808795"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808796" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mangat_angad" style="position: relative;"> <img src='https://userpic.codeforces.org/1449578/avatar/d3cadb0c26e0c11f.jpg'/> </a> <div><a href="/profile/mangat_angad" title="Specialist mangat_angad" class="rated-user user-cyan">mangat_angad</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808796" href="?#comment-808796" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808796" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1449578" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808796"> <div class="moveup"> <div class="ttypography"><p>I feel like such an idiot for not being able to understand problem C (Div2). For some reason I thought the nodes were connected like this — 1-&gt;2-&gt;3-&gt;....-&gt;N and that we had to minimise answer by adding other edges (of negative weight in case they dont give a negative cycle) to this graph.</p></div> </div> </div> <div class="reply info"> <a class="comment-808796 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808796 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808796"> <li> <div class="comment"> <table class="comment-table" commentId="808896" commentParentId="808796"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808896" href="?#comment-808896" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808796" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808896" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808896"> <div class="moveup"> <div class="ttypography"><p>But that's exactly what I did, and the final answer is the sum of the array — sum of all subarrays. <a href="https://codeforces.com/contest/1541/submission/120611950">120611950</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808896 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808896 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808896"> <li> <div class="comment"> <table class="comment-table" commentId="808941" commentParentId="808896"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808941" href="?#comment-808941" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808896" style="font-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="808941" 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="808941" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808941"> <div class="moveup"> <div class="ttypography"><p>No, that's not what you did. To compute the answer via the method described above, you would have to compute how many elements are lesser than the current element at any given iteration and add them and also keep and their count using a Fenwick tree/ BIT. That's the incorrect approach though because sorting would be more optimal.</p></div> </div> </div> <div class="reply info"> <a class="comment-808941 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808941 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808941"> <li> <div class="comment"> <table class="comment-table" commentId="808952" commentParentId="808941"> <tr> <td class="left"> <div style="position: absolute; left: 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/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808952" href="?#comment-808952" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808941" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808952" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808952"> <div class="moveup"> <div class="ttypography"><p>Sorry if I misunderstood things. mangat_angad only mentioned adding negative weighed edges to the 1-&gt;2-&gt;3-&gt;...N graph, which is what I thought to arrive at my solution. The array I mentioned is indeed sorted and formed by distance differences which are the weights in the 1-&gt;2-&gt;3-&gt;...N graph. Unfortunately I'm still too noob to understand the tree structures you mentioned.</p></div> </div> </div> <div class="reply info"> <a class="comment-808952 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808952 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808952"> <li> <div class="comment"> <table class="comment-table" commentId="808955" commentParentId="808952"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808955" href="?#comment-808955" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808952" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808955" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808955"> <div class="moveup"> <div class="ttypography"><p>Nothing unfortunate about it, logic trumps everything </p></div> </div> </div> <div class="reply info"> <a class="comment-808955 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808955 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808955"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808797" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808797" href="?#comment-808797" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808797" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808797"> <div class="moveup"> <div class="ttypography"><p>Just want to apologize to authors for the stupidest question, I misread the task..</p></div> </div> </div> <div class="reply info"> <a class="comment-808797 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808797 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808797"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808813" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808813" href="?#comment-808813" style="font-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="808813" 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="808813" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808813"> <div class="moveup"> <div class="ttypography"><p>Can someone tell me the meaning of this line in problem Div2D/Div1B<br /></p> <blockquote><p>Note that, until reaching, l every possible process still has the same probability of reaching b before a. Therefore, we can assume that the process has reached l and calculate the probability from there.</p> </blockquote><p>What same probability are they talking about?</p></div> </div> </div> <div class="reply info"> <a class="comment-808813 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808813 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808813"> <li> <div class="comment"> <table class="comment-table" commentId="808831" commentParentId="808813"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808831" href="?#comment-808831" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808813" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808831" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808831"> <div class="moveup"> <div class="ttypography"><p>Here's what it's trying to say:</p><p>Suppose we start by marking the root. To mark a or b, we must first mark the lca, so we may assume that the lca has just been marked.</p></div> </div> </div> <div class="reply info"> <a class="comment-808831 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808831 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808831"> <li> <div class="comment"> <table class="comment-table" commentId="808840" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808840" href="?#comment-808840" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808840" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808840"> <div class="moveup"> <div class="ttypography"><p>And what does this line mean? <em>&quot;The problem can be rephrased as having two stacks of size dist(l,a) and dist(l,b) with an arbitrary p to remove a node from one of the two stack (and 1−2p to nothing) and finding the probability that dist(l,b) reaches zero before dist(l,a).&quot;</em></p></div> </div> </div> <div class="reply info"> <a class="comment-808840 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808840 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808840"> <li> <div class="comment"> <table class="comment-table" commentId="808857" commentParentId="808840"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808857" href="?#comment-808857" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808840" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808857" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808857"> <div class="moveup"> <div class="ttypography"><p>Once you've reached the lca $$$l$$$, in a single step you either step closer to $$$a$$$, step closer to $$$b$$$, or step closer to neither.</p></div> </div> </div> <div class="reply info"> <a class="comment-808857 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808857 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808857"> <li> <div class="comment"> <table class="comment-table" commentId="808862" commentParentId="808857"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808862" href="?#comment-808862" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808857" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808862" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808862"> <div class="moveup"> <div class="ttypography"><p>Can you add implementation for this problem please?</p></div> </div> </div> <div class="reply info"> <a class="comment-808862 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808862 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808862"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808849" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808849" href="?#comment-808849" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808849" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808849"> <div class="moveup"> <div class="ttypography"><p>So, we mark lca first (of course). But why wouldn't it affect the final probability of reaching b before a? I mean, why is it sufficient to calculate the probability after marking lca?</p></div> </div> </div> <div class="reply info"> <a class="comment-808849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808849"> <li> <div class="comment"> <table class="comment-table" commentId="808873" commentParentId="808849"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808873" href="?#comment-808873" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808849" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808873" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808873"> <div class="moveup"> <div class="ttypography"><p>Before marking the lca, there is no way to make more progress towards $$$b$$$ than $$$a$$$ or vice versa. The subset of marked vertices also does not change the probability of moving towards $$$a$$$ or $$$b$$$ after reaching the lca because we're choosing uniformly at random and exactly two vertices are of interest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808873 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808873 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808873"> <li> <div class="comment"> <table class="comment-table" commentId="808883" commentParentId="808873"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808883" href="?#comment-808883" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808873" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808883" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808883"> <div class="moveup"> <div class="ttypography"><p>Now I get it. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808883 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808883 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808883"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808814" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808814" href="?#comment-808814" style="font-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="808814" 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="808814" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808814"> <div class="moveup"> <div class="ttypography"><p>So, my Solution for <strong>Div1 Problem B</strong> / <strong>Div2 Problem D</strong> / <strong>1540B — Tree Array</strong>:</p><p>Chose two Nodes $$$A$$$ and $$$B$$$ with $$$A&gt;B$$$. </p><p><strong>First DFS:</strong> Find the path from $$$A$$$ to $$$B$$$. I call it $$$path_p$$$. On $$$path_p$$$ mark the distance to $$$B$$$ for each node. </p><p><strong>Second DFS:</strong> For each remaining node $$$N$$$ find the shortest path to $$$path_p$$$. It will hit it at some node of the $$$path_p$$$ which has some distance $$$D$$$ marked on it. We mark $$$N$$$ with $$$D$$$. (See comment below for image.)</p><p><strong>Calculation:</strong> For each node $$$N$$$ we can calculate $$$P_i$$$. $$$P_i$$$ is the probability to reach Node $$$B$$$ before we reach Node $$$A$$$. We sum $$$P_i$$$ for each node. $$$P_i$$$ is also the probability, that the pair of Nodes $$$A$$$ and $$$B$$$ with starting node $$$N$$$ will contribute to the inversion sum. </p><p><strong>Iteration:</strong> We need to repeat this for each pair $$$A$$$ and $$$B$$$. In the end we divide the answer by $$$n$$$, the amount of nodes (the probability to start with Node $$$N$$$). </p><p>This algorithm is $$$O(N^3)$$$. See my Solution <a href="/contest/1540/submission/120603369" title="Посылка 120603369 от OleschY">120603369</a></p> <div class="spoiler"><b class="spoiler-title">How to calculate P_i</b><div class="spoiler-content" style="display: none;"><p>I wrote myself a small helper DP-program to find the regularities. Let $$$D$$$ be the Distance between $$$A$$$ and $$$B$$$ and $$$d$$$ be the distance from the node $$$N$$$ to $$$B$$$. My educated guess was: $$$P_i=\frac{\sum_{i=0}^{d-1}\binom{D-1}{i} }{2^{D-1}}$$$</p> <div class="spoiler"><b class="spoiler-title">Helper Program</b><div class="spoiler-content" style="display: none;"><p>It checks for a path of some length for each Intervall $$$[A,B]$$$ which is already visited, what the probability to reach one node before the other is. </p> <pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; int solve(int n) { vector&lt;vector&lt;double&gt;&gt; dp(n, vector&lt;double&gt;(n, 0)); for(int i = 0; i &lt; n; ++i) { dp[0][i] = 1; dp[i][n - 1] = 0; } dp[0][n - 1] = -1; for(int w = n; w &gt;= 0; w--) { for(int i = 1; i + w &lt; n - 1; i++) { int l = i; int r = w + i; dp[l][r] = 0.5 * (dp[l - 1][r] + dp[l][r + 1]); } } cout &lt;&lt; n &lt;&lt; &quot;\n\n&quot;; for(int i = 0; i &lt; n; i++) { cout &lt;&lt; dp[i][i]*(1&lt;&lt;(n-2)) &lt;&lt; &quot;\n&quot;; } cout &lt;&lt; &quot;\n\n\n\n&quot;; return 0; } //====================== // Technical stuff //====================== int main() { int ntest = 12; for(int test = 2; test &lt; ntest; ++test) { solve(test); } return 0; } </code></pre></div></div></div></div></div> </div> </div> <div class="reply info"> <a class="comment-808814 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808814 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808814"> <li> <div class="comment"> <table class="comment-table" commentId="808843" commentParentId="808814"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808843" href="?#comment-808843" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808814" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808843" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808843"> <div class="moveup"> <div class="ttypography"><p>Can you explain your solution in a little bit more detail? :')</p></div> </div> </div> <div class="reply info"> <a class="comment-808843 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808843 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808843"> <li> <div class="comment"> <table class="comment-table" commentId="808869" commentParentId="808843"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808869" href="?#comment-808869" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808843" style="font-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="808869" 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="808869" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808869"> <div class="moveup"> <div class="ttypography"><p>Oof, I can give you an image, that shows how the distances from the two DFS are distributed on an example. You can see Nodes $$$A$$$ and $$$B$$$ and the numbers are the distances we write into the nodes. </p><p><img alt=" " src="/predownloaded/d8/2f/d82f98ecd2c1b4bd15b3c40e62476f6ae2741a64.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>If you have specific questions about some steps go ahead and ask. </p></div> </div> </div> <div class="reply info"> <a class="comment-808869 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808869 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808869"> <li> <div class="comment"> <table class="comment-table" commentId="810069" commentParentId="808869"> <tr> <td class="left"> <div style="position: absolute; left: 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/Mrajaryan" style="position: relative;"> <img src='https://userpic.codeforces.org/1377953/avatar/e904b3a3a2eac1ad.jpg'/> </a> <div><a href="/profile/Mrajaryan" title="Newbie Mrajaryan" class="rated-user user-gray">Mrajaryan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 15:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810069" href="?#comment-810069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808869" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810069" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1377953" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810069"> <div class="moveup"> <div class="ttypography"><p>what does the dp states mean in your helper program? I am unable to understand. Can you please explain?</p></div> </div> </div> <div class="reply info"> <a class="comment-810069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810069"> <li> <div class="comment"> <table class="comment-table" commentId="810097" commentParentId="810069"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 18:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810097" href="?#comment-810097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-810069" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810097"> <div class="moveup"> <div class="ttypography"><p>You have Nodes $$$1$$$ through $$$N$$$, neighbouring IDs are connected. The state $$$dp[l][r]$$$ is the probability, that node $$$N$$$ will be reached before node $$$1$$$ with all the nodes $$$l$$$ through $$$r$$$ marked already. Obviously $$$dp[1][x]=0$$$ and $$$dp[x][N]=1$$$ ($$$dp[1][N]$$$ can't happen). The recurrence is $$$dp[l][r]=(dp[l-1][r]+dp[l][r+1])/2$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-810097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808818" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808818" href="?#comment-808818" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808818" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808818"> <div class="moveup"> <div class="ttypography"><p>I can't grasp the editorial of Div 2 D/ Div 1 B. Can somebody provide a more intuitive explanation?</p></div> </div> </div> <div class="reply info"> <a class="comment-808818 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808818 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808818"> <li> <div class="comment"> <table class="comment-table" commentId="808821" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:45">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808821" href="?#comment-808821" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808821" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808821"> <div class="moveup"> <div class="ttypography"><p>same :(</p></div> </div> </div> <div class="reply info"> <a class="comment-808821 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808821 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808821"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808861" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808861" href="?#comment-808861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808861" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808861"> <div class="moveup"> <div class="ttypography"><p>Step 1. use linearity of expectation. The answer is</p> <center>$$$\sum_{a&lt;b} P(b\text{ appears before }a). $$$</center><p>Step 2: Observe that if we start by marking a vertex $$$c$$$ on the path between $$$a$$$ and $$$b$$$, and suppose the next marked vertex on the path is $$$d$$$. Then, the probability that $$$d$$$ is between $$$c$$$ and $$$a$$$ and the probability that $$$d$$$ is between $$$c$$$ and $$$b$$$ are both $$$1/2$$$. This is because there are only two choices for $$$d$$$ and we're choosing uniformly at random. This means that the answer only depends on $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p><p>Step 3: run a dp to calculate the probability that we mark $$$b$$$ before $$$a$$$ given $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808861"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808833" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808833" href="?#comment-808833" style="font-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="808833" 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="808833" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-72" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-72</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808833"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin &gt;&gt; t; while(t--){ int n; cin &gt;&gt; n; long long arr[n]; for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0; for(int i = 0; i &lt; n — 1; i++){ for(int j = arr[i] — 2 — i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } } } cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;; } return 0; }</p><p>/* Accepted code A different approach using arrays (as I don't know what vectors are, haven't read that) I hope this is a optimal approach. Any suggestions related to this are whole-heartedly welcomed. Also, please guide me how could I have optimized the code to a much extent. Thanks in advance! Keep programming! */</p></div> </div> </div> <div class="reply info"> <a class="comment-808833 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808833 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808833"> <li> <div class="comment"> <table class="comment-table" commentId="808844" commentParentId="808833"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808844" href="?#comment-808844" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808833" style="font-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="808844" 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="808844" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-35" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808844"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-808844 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808844 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808844"> <li> <div class="comment"> <table class="comment-table" commentId="808863" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808863" href="?#comment-808863" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808863" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808863"> <div class="moveup"> <div class="ttypography"><p>Not studied yet, I'm still a beginner, but planning to start soon. Thanks for the guidance.</p></div> </div> </div> <div class="reply info"> <a class="comment-808863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808863"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808879" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808879" href="?#comment-808879" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808879" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808879"> <div class="moveup"> <div class="ttypography"><p>once upon a time, I also did problems while not know what vectors are. sad times :'(</p></div> </div> </div> <div class="reply info"> <a class="comment-808879 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808879 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808879"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808926" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808926" href="?#comment-808926" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808926" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808926"> <div class="moveup"> <div class="ttypography"><p>There's no issue in not knowing vectors. Yes they are important I agree but not knowing vectors should not be discouraged. I became expert here without knowing anything about vectors plus he is a beginner so he shouldn't be discouraged like this.</p></div> </div> </div> <div class="reply info"> <a class="comment-808926 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808926 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808926"> <li> <div class="comment"> <table class="comment-table" commentId="808927" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Tech.Maniac" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Tech.Maniac" title="Expert Tech.Maniac" class="rated-user user-blue">Tech.Maniac</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808927" href="?#comment-808927" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808927" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1242860" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808927"> <div class="moveup"> <div class="ttypography"><p>+1, I agree with you. Same I was expert last year solely using arrays</p></div> </div> </div> <div class="reply info"> <a class="comment-808927 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808927 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808927"> <li> <div class="comment"> <table class="comment-table" commentId="809201" commentParentId="808927"> <tr> <td class="left"> <div style="position: absolute; left: 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/Yash.Amin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Yash.Amin" title="Specialist Yash.Amin" class="rated-user user-cyan">Yash.Amin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809201" href="?#comment-809201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808927" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809201" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-28" data-commentUserId="1226462" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-28</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809201"> <div class="moveup"> <div class="ttypography"><p>Bas kar bsdk kitna jhooth bolega</p></div> </div> </div> <div class="reply info"> <a class="comment-809201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809201"> <li> <div class="comment"> <table class="comment-table" commentId="809215" commentParentId="809201"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809215" href="?#comment-809215" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809215" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809215"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-blue" href="/profile/Yash.Amin" title="Эксперт Yash.Amin">Yash.Amin</a> Could you please refrain from using foul language on educational discussions. Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-809215 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809215 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809215"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808928" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808928" href="?#comment-808928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808928" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808928"> <div class="moveup"> <div class="ttypography"><p>Ah my bad, I did not want to come across as being arrogant, but I was genuinely confused that some people did not know vectors although they are using C++.</p></div> </div> </div> <div class="reply info"> <a class="comment-808928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808928"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808839" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamkiller04" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dreamkiller04" title="Newbie dreamkiller04" class="rated-user user-gray">dreamkiller04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808839" href="?#comment-808839" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2089608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808839"> <div class="moveup"> <div class="ttypography"><p>Please add implementations too.</p></div> </div> </div> <div class="reply info"> <a class="comment-808839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808839"> <li> <div class="comment"> <table class="comment-table" commentId="809106" commentParentId="808839"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809106" href="?#comment-809106" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808839" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809106" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809106"> <div class="moveup"> <div class="ttypography"><p>Simply running two loops and checking every case would give a TLE. So, we might want to minimize the number of operations. For this, we would only consider the cases where the sum of indices is a multiple of an element.</p><p>For this, we would first create two loops, one within the other, first loop iterating i from 0 to (n — 1) with an incrementation of 1. By observation, we can see that the first index for which the sum of indices will be a multiple of arr[i] is (arr[i] — 2 — i).</p><p>So, in the nested loop we will run j = (arr[i] — 2 — i) till (n — 1) with an incrementation of arr[i]. We would ignore the cases where j &lt; 0 or j &gt;= n.</p><p>Finally, we need to check for how many cases this holds (arr[i] * arr[j] = i + j + 2 and j &gt; i).</p><p>Suggestions are welcomed!</p></div> </div> </div> <div class="reply info"> <a class="comment-809106 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809106 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809106"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808842" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808842" href="?#comment-808842" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808842" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-64" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-64</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808842"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){</p><p>ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);</p><p>int t;</p><p>cin &gt;&gt; t;</p><p>while(t--){</p><p>int n;</p> <pre>cin &gt;&gt; n;</pre><p>long long arr[n];</p> <pre>for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0;</pre><p>for(int i = 0; i &lt; n — 1; i++){</p> <pre>for(int j = arr[i] &amp;mdash; 2 &amp;mdash; i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } }</pre><p>}</p><p>cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;;</p><p>}</p> <pre>return 0;</pre><p>}</p><p>/* Accepted code</p><p>A different approach using arrays (as I don't know what vectors are, haven't read that)</p><p>I hope this is a optimal approach.</p><p>Any suggestions related to this are whole-heartedly welcomed.</p><p>Also, please guide me how could I have optimized the code to a much extent.</p><p>Thanks in advance!</p><p>Keep programming! </p><p>*/</p></div> </div> </div> <div class="reply info"> <a class="comment-808842 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808842 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808842"> <li> <div class="comment"> <table class="comment-table" commentId="808851" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808851" href="?#comment-808851" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808851" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808851"> <div class="moveup"> <div class="ttypography"><p>Use spoilers for writing codes, please!</p></div> </div> </div> <div class="reply info"> <a class="comment-808851 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808851 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808851"> <li> <div class="comment"> <table class="comment-table" commentId="808870" commentParentId="808851"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808870" href="?#comment-808870" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808851" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808870" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808870"> <div class="moveup"> <div class="ttypography"><p>Actually, this is my first comment. Don't know much of this stuff as of now, but I'll surely take care of it the very next time.</p></div> </div> </div> <div class="reply info"> <a class="comment-808870 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808870 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808870"> <li> <div class="comment"> <table class="comment-table" commentId="809760" commentParentId="808870"> <tr> <td class="left"> <div style="position: absolute; left: 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/sus" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sus" title="Pupil sus" class="rated-user user-green">sus</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 05:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809760" href="?#comment-809760" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808870" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809760" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1749651" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809760"> <div class="moveup"> <div class="ttypography"><p>what problem is your code for</p></div> </div> </div> <div class="reply info"> <a class="comment-809760 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809760 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809760"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808884" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sevlll777" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sevlll777" title="Grandmaster sevlll777" class="rated-user user-red">sevlll777</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808884" href="?#comment-808884" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808884" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="839333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808884"> <div class="moveup"> <div class="ttypography"><p>NICE CODESTYLE!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-808884 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808884 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808884"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809084" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cj2021" style="position: relative;"> <img src='https://userpic.codeforces.org/1927237/avatar/b64ff59bd9dcf385.jpg'/> </a> <div><a href="/profile/cj2021" title="Newbie cj2021" class="rated-user user-gray">cj2021</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809084" href="?#comment-809084" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809084" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1927237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809084"> <div class="moveup"> <div class="ttypography"><p>What is &amp;mdash?</p><p>Just curious to know as haven't seen it before.</p></div> </div> </div> <div class="reply info"> <a class="comment-809084 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809084 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809084"> <li> <div class="comment"> <table class="comment-table" commentId="809097" commentParentId="809084"> <tr> <td class="left"> <div style="position: absolute; left: 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/klahsiv" style="position: relative;"> <img src='https://userpic.codeforces.org/1590145/avatar/1bf86ae3d48e55b.jpg'/> </a> <div><a href="/profile/klahsiv" title="Expert klahsiv" class="rated-user user-blue">klahsiv</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809097" href="?#comment-809097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809084" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590145" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809097"> <div class="moveup"> <div class="ttypography"><p>it is minus (-).</p></div> </div> </div> <div class="reply info"> <a class="comment-809097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808848" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/willy108" style="position: relative;"> <img src='https://userpic.codeforces.org/1439320/avatar/d7f79ed4e8b32e9a.jpg'/> </a> <div><a href="/profile/willy108" title="Master willy108" class="rated-user user-orange">willy108</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808848" href="?#comment-808848" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808848" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="1439320" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808848"> <div class="moveup"> <div class="ttypography"><p>Div2 B can also be done in O(NsqrtN). We know that for a given pair of indeces i+j &lt; 2n, so any pair that a[i] * a[j] &lt; 2n will have to have one of the two terms be &lt;= sqrt(n) (with some off by one errors of course). So the algorithm is to store an array of pairs [array value, index] and sort that array by the value. If the array value is &lt;= sqrt(2n) we can naively loop over the rest of the array in O(n) time and check (be careful about overcount), and if the value is &gt; sqrt(n), we can ignore it. This works since when a[i] * a[j] &lt; 2n one of a[i] or a[j] has to be &lt;= sqrt(2n) and as a result, every pair will be counted.</p></div> </div> </div> <div class="reply info"> <a class="comment-808848 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808848 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808848"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808860" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bcollet" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bcollet" title="Master bcollet" class="rated-user user-orange">bcollet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808860" href="?#comment-808860" style="font-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="808860" 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="808860" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="858059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808860"> <div class="moveup"> <div class="ttypography"><p>I don't understand in div1 C why it's prefix of b, in the case i=3 we have $$$a_1+a_2+a_3=f_1+f_1+b_1+f_1+b_1+b_2$$$ so $$$f_1=(ap_i-2b_1-b_2)$$$ I believe the general formula is something in the taste of $$$f_1=(ap_i-ibp_{i-1}+bpt_{i-1})/i$$$ where bpt_i=b_1+2b_2+...+ib_i, I think I miss something<br />Edit: corrected</p></div> </div> </div> <div class="reply info"> <a class="comment-808860 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808860 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808860"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808865" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ParsaS" style="position: relative;"> <img src='https://userpic.codeforces.org/1590150/avatar/dc2d8c002d2c5e1e.jpg'/> </a> <div><a href="/profile/ParsaS" title="Candidate Master ParsaS" class="rated-user user-violet">ParsaS</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808865" href="?#comment-808865" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808865" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590150" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808865"> <div class="moveup"> <div class="ttypography"><p>Nice problems. thanks for almost fast editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-808865 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808865 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808865"> <li> <div class="comment"> <table class="comment-table" commentId="808871" commentParentId="808865"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/E404_Not_Found" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/E404_Not_Found" title="Expert E404_Not_Found" class="rated-user user-blue">E404_Not_Found</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808871" href="?#comment-808871" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808865" style="font-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="808871" 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="808871" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1662858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808871"> <div class="moveup"> <div class="ttypography"><p>Yes thanks for fast editorial :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808871 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808871 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808871"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808890" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vikash_8090_b" style="position: relative;"> <img src='https://userpic.codeforces.org/1969032/avatar/a0f23c893ae54e74.jpg'/> </a> <div><a href="/profile/vikash_8090_b" title="Newbie vikash_8090_b" class="rated-user user-gray">vikash_8090_b</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808890" href="?#comment-808890" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808890" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="1969032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808890"> <div class="moveup"> <div class="ttypography"><p>is there anyone who can't even solve one question of today's contest ..</p></div> </div> </div> <div class="reply info"> <a class="comment-808890 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808890 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808890"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808892" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808892" href="?#comment-808892" style="font-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="808892" 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="808892" class="CommentVoteFrame" data-commentRating="-6" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808892"> <div class="moveup"> <div class="ttypography"><p>Deleted :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808892 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808892 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808892"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808918" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prituladima" style="position: relative;"> <img src='https://userpic.codeforces.org/116750/avatar/ca46d0256a294b26.jpg'/> </a> <div><a href="/profile/prituladima" title="Pupil prituladima" class="rated-user user-green">prituladima</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808918" href="?#comment-808918" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808918" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="116750" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808918"> <div class="moveup"> <div class="ttypography"><p>Please explain div2c/div1a problem a little bit more. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808918 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808918 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808918"> <li> <div class="comment"> <table class="comment-table" commentId="808921" commentParentId="808918"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808921" href="?#comment-808921" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808918" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808921" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808921"> <div class="moveup"> <div class="ttypography"><p>Try out this <a href="https://youtube.com/c/MagentaCobra">channel</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808921 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808921 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808921"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808950" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jakab922" style="position: relative;"> <img src='https://userpic.codeforces.org/53532/avatar/f9515e974f3ebcb1.jpg'/> </a> <div><a href="/profile/jakab922" title="Specialist jakab922" class="rated-user user-cyan">jakab922</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808950" href="?#comment-808950" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808950" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="53532" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808950"> <div class="moveup"> <div class="ttypography"><p>I don't really understand the need for a recursive function for the stack emptying probabilities in <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a>. I mean given that you have a stack of size <code>n</code> and and <code>m</code> you can basically have an array of size <code>n + m</code> filled with <code>0</code>s and <code>1</code>s where <code>0</code> at the <code>i</code>th place means that the <code>i</code>th element was taken from the first stack. Any such array which has <code>n</code> <code>0</code>s and <code>m</code> <code>1</code>s correspond to one process and it's easy to see that whoever takes the last spot in the array gets emptied later which gives an easy way to calculate the probabilities. Namely $$$\binom{n + m - 1}{n - 1} / \binom{n + m}{n}$$$ for the first and similar to the other. </p></div> </div> </div> <div class="reply info"> <a class="comment-808950 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808950 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808950"> <li> <div class="comment"> <table class="comment-table" commentId="808959" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cuom1999" style="position: relative;"> <img src='https://userpic.codeforces.org/253776/avatar/934152bc42a0b10c.jpg'/> </a> <div><a href="/profile/cuom1999" title="Grandmaster cuom1999" class="rated-user user-red">cuom1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808959" href="?#comment-808959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="253776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808959"> <div class="moveup"> <div class="ttypography"><p>If $$$m=2$$$ and $$$n=1$$$, your approach gives $$$\frac{1}{3}$$$. The correct answer should be $$$\frac{1}{4}$$$. </p><p>P/S: I'm also curious if there is any combinatoric approach for this,<a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808959"> <li> <div class="comment"> <table class="comment-table" commentId="809004" commentParentId="808959"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809004" href="?#comment-809004" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809004" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809004"> <div class="moveup"> <div class="ttypography"><p>I would guess that there’s no easy closed form. You can evaluate in $$$O(n)$$$ however by counting right up paths from $$$(a,0)$$$ to $$$(x,y)$$$ for all $$$a$$$ and multiplying by $$$2^{-steps}$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-809004 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809004 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809004"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809366" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/geekpradd" style="position: relative;"> <img src='https://userpic.codeforces.org/367430/avatar/427394aa7f5a63a0.jpg'/> </a> <div><a href="/profile/geekpradd" title="Candidate Master geekpradd" class="rated-user user-violet">geekpradd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809366" href="?#comment-809366" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809366" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="367430" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809366"> <div class="moveup"> <div class="ttypography"><p>The problem with this is that all the possibilities are not equilikely, consider $$$m=2, n=1$$$ and let $$$1$$$ denote entries from the stack of size $$$n$$$. Then the probability of obtaining $$$100$$$ is $$$1/2$$$, while obtaining $$$010$$$ and $$$001$$$ has a probability of $$$1/4$$$. Your approach assumes a uniform prior probability (in which case the answer is indeed $$$1/3$$$ whereas here it is $$$1/4$$$ which is the probability of getting $$$001$$$)</p></div> </div> </div> <div class="reply info"> <a class="comment-809366 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809366 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809366"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thunderboltz" style="position: relative;"> <img src='https://userpic.codeforces.org/1170396/avatar/4f017b259605bc5c.jpg'/> </a> <div><a href="/profile/thunderboltz" title="Newbie thunderboltz" class="rated-user user-gray">thunderboltz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808951" href="?#comment-808951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170396" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808951"> <div class="moveup"> <div class="ttypography"><p>Problem Div2C/Div1A, Plz somebody explain 3rd hint. I didn't get why this condition must be true </p><p><code>The sum of the values of edges with positive weight must be ≥ the maximum value in the array.</code></p></div> </div> </div> <div class="reply info"> <a class="comment-808951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808951"> <li> <div class="comment"> <table class="comment-table" commentId="808995" commentParentId="808951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808995" href="?#comment-808995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808995" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808995"> <div class="moveup"> <div class="ttypography"><p>I like to think about C this way: The cheapest node is the root, and the most expensive node, X, is the one with the highest value, D. Therefore no matter how we make our edges, we need at least 1 path from node to X with distance D. So let's build 1 single edge of positive weight from 1 to X with weight D.</p><p>Now from node X, all other nodes are &lt;= D. We can use negative edges to go there. Now the problem just becomes &quot;assign as many negative edges as possible&quot; to the rest of the nodes. </p></div> </div> </div> <div class="reply info"> <a class="comment-808995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808995"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808971" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808971" href="?#comment-808971" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808971" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808971"> <div class="moveup"> <div class="ttypography"><p>In problem <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a> I agree with everything up to:</p> <blockquote><p>Once l is reached, we now note that the probability that the process &quot;gets closer&quot; to b is always equal to the probability of getting closer to a.</p> </blockquote><p>I agree with this quote if it was about each individual set of marked nodes and single step for them. Because for any individual set of marked nodes, those probabilities is just one over the number of options at the moment. But I don't understand why I should forget about everything else what happens with other parts of tree, because after single step which is neither towards <strong>a</strong> neither towards <strong>b</strong>, the number of options (nodes we can mark on next step) may change.</p></div> </div> </div> <div class="reply info"> <a class="comment-808971 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808971 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808971"> <li> <div class="comment"> <table class="comment-table" commentId="809006" commentParentId="808971"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809006" href="?#comment-809006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808971" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809006" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809006"> <div class="moveup"> <div class="ttypography"><p>That is correct, but to see how it stays the same you can think of it inductively. Use strong induction and assume probability is the same no matter what the state of the tree is. Then from $$$(x,y)$$$ you always have an equal probability of ending up in one of the two states you can transition to because $$$p$$$ is always the same. Every scenario you enter one state, there’s another scenario with the same probability that enters the other state. So, the probability of entering one of the two states is the same as the other, thus $$$0.5$$$. Hopefully that makes things more clear.</p></div> </div> </div> <div class="reply info"> <a class="comment-809006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809006"> <li> <div class="comment"> <table class="comment-table" commentId="809113" commentParentId="809006"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809113" href="?#comment-809113" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809006" style="font-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="809113" 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="809113" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809113"> <div class="moveup"> <div class="ttypography"><p>Oh thanks, it's clear now. So, base of induction is when only <strong>l</strong> reached, and we can show that probability to make step towards <strong>a</strong> and <strong>b</strong> is same because for each individual set you can go from <strong>l</strong> to <strong>b</strong> instead of going from <strong>l</strong> into <strong>a</strong>, using exactly same steps in between (those steps which doesn't change distances to <strong>a</strong> and <strong>b</strong>). And similar holds for next steps.</p></div> </div> </div> <div class="reply info"> <a class="comment-809113 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809113 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809113"> <li> <div class="comment"> <table class="comment-table" commentId="821713" commentParentId="809113"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 08:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821713" href="?#comment-821713" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809113" style="font-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="821713" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="821713" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-821713"> <div class="moveup"> <div class="ttypography"><p>Can you explain this?</p><p>Assume $$$X$$$ is initially node we chose. Then define a function $$$g$$$ :</p><p>$$$g[a][b][STATE]$$$ = probability to reach a before b while state of the tree we reach is $$$STATE$$$, and $$$a$$$, $$$b$$$ is length of path.</p><p><img alt=" " src="/predownloaded/c2/32/c232d053fe3fbd1dedc06e56db58a7c139157987.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>follow the image, I can see : $$$g[a][b][STATE_x] = \frac{1}{4} (g[a][b][STATE_d] + g[a][b][STATE_e] + g[a — 1][b][closer_a] + g[a][b — 1][closer_b])$$$</p><p>It can easy see that the probability can change. Or I wrong in some where?</p></div> </div> </div> <div class="reply info"> <a class="comment-821713 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821713 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821713"> <li> <div class="comment"> <table class="comment-table" commentId="821861" commentParentId="821713"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 18:25">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821861" href="?#comment-821861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821713" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="821861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-821861"> <div class="moveup"> <div class="ttypography"><p>I'll hide my long explanation under spoiler</p> <div class="spoiler"><b class="spoiler-title">horrible wall of text</b><div class="spoiler-content" style="display: none;"><p>To put things into words, I want to define some things. First, suppose we marked some $$$s_1, s_2, s_3 ... s_k$$$ vertices in exact this order. Then, let $$$P(s)$$$ to be probability to mark them in this sequence. It can be decomposed into $$$P(s) = p_1 \cdot p_2 \cdot p_3 \cdot ... \cdot p_k$$$ where $$$p_i = 1/o_{i-1}$$$ where $$$o_i$$$ is number of options at step $$$i$$$ — number of opened vertices, except $$$p_0 = 1/n$$$, or $$$o_0 = n$$$.</p><p>Then, let $$$l = LCA(a, b)$$$ where $$$LCA$$$ is lowest common ancestor. Then, let $$$x_v$$$ to be some sort of 'cost'. For each $$$v$$$ on path between $$$a$$$ and $$$l$$$ it will be distance to $$$l$$$, and $$$-1$$$ everywhere else. Similarly, for each $$$v$$$ on path between $$$b$$$ and $$$l$$$ let $$$y_v$$$ to be distance to $$$l$$$ and $$$-1$$$ everywhere else. Let</p> <center>$$$ A(s) = \max\limits_{v\in s}x_v \\ B(s) = \max\limits_{v\in s}y_v $$$</center><p>Then $$$A(s)$$$ is equal to how far we reach $$$a$$$, and $$$B(s)$$$ is equal to how far we reach $$$b$$$. Let say we are in situation $$$(A(s), B(s))$$$ after marking $$$s$$$, and therefore situation is pair of numbers. Situation $$$(-1,-1)$$$ corresponds that no vertex is marked on path from $$$a$$$ to $$$b$$$. Situation $$$(0,0)$$$ corresponds to only $$$l$$$ marked on path from $$$a$$$ to $$$b$$$. And situation $$$(1,0)$$$ corresponds to $$$l$$$ and single vertex towards $$$a$$$ is marked.</p><p>Finally, let say sequence of marks $$$s$$$ reached state $$$(A(s), B(s))$$$ if either $$$A(s) = x_{s_k}$$$ or $$$B(s) = y_{s_k}$$$, in other words, last vertex is on path from $$$a$$$ to $$$b$$$ and it did change situation.</p><p>Now, what we want to prove is following:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha+1,\beta)} P(s) = \sum\limits_{s\;reached\;(\alpha,\beta+1)} P(s)$$$</center><p><strong>For some fixed</strong> $$$s_1$$$, which is root we chosen. And the way we prove it is that $$$s$$$ that is reached $$$(\alpha+1,\beta)$$$ consists of $$$u$$$ that reached $$$(\alpha,\beta)$$$ plus additional steps: $$$w$$$ plus $$$s_k$$$. So $$$s = u..w..s_k$$$ where $$$..$$$ is concatenation. It's easy to see what none of vertices from $$$w$$$ is on path from $$$a$$$ to $$$b$$$. Also, it's easy to see that we could instead of choosing $$$s_k$$$ could choose vertex $$$z$$$ towards $$$b$$$, and it would have same probability. In other words $$$P(s) = P(u..w..z)$$$. And this $$$u..w..z$$$ should reach state $$$(\alpha, \beta+1)$$$. So it should be in right side sum of our equation we want to prove.</p><p>So, for any $$$s$$$ from left sum, we can make $$$s'$$$ from right sum in unique way, and it will have same $$$P(s) = P(s')$$$. Similarly, for any $$$s$$$ from right sum, we can make $$$s'$$$ from left sum in unique way, and it will have same $$$P(s) = P(s')$$$. So this is bijection, and each element from left sum corresponds to element from right sum with same value, so those sums should have same value. Therefore it's equality.</p><p>Initially I wanted to trim $$$s$$$ from $$$(\alpha+1,\beta)$$$ to $$$(\alpha,\beta)$$$ and show similar thing based on following sum:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha,\beta)} P(s)$$$</center><p>Which is probability to reach state $$$(\alpha, \beta)$$$, but luckily it didn't required. I'll use notation $$$P(reach(\alpha, \beta))$$$ for this probability.</p><p>Thing that is not covered though: why this equality can be translated into probability $$$= 1/2$$$? Well, from $$$(\alpha, \beta)$$$ you eventually will reach either $$$(\alpha+1,\beta)$$$ or $$$(\alpha,\beta+1)$$$, so you can see this as example of Law of total probability. $$$P(reach(\alpha, \beta)) = P(reach (\alpha+1, \beta)) + P(reach (\alpha, \beta+1))$$$, because events $$$(\alpha+1,\beta)$$$ and $$$(\alpha,\beta+1)$$$ are disjoint events given $$$(\alpha, \beta)$$$ is reached. And we proved they have equal probability so $$$P(reach(\alpha, \beta)) = 2\cdot P(reach (\alpha+1, \beta))$$$, so $$$P(reach (\alpha+1, \beta)) = 1/2\cdot P(reach(\alpha, \beta))$$$ which we actually use.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-821861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821861"> <li> <div class="comment"> <table class="comment-table" commentId="822027" commentParentId="821861"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/28/2021 13:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822027" href="?#comment-822027" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821861" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="822027" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822027"> <div class="moveup"> <div class="ttypography"><p>Oh, sorry, there is one missing part. We proved $$$P(reached(\alpha+1,\beta))=P(reached(\alpha,\beta+1))$$$ <strong>given</strong> $$$(\alpha,\beta)$$$ is reached, but this is actually what we need. This <strong>given</strong> condition is what I missed. Without <strong>given</strong> we could reach $$$(\alpha+1,\beta)$$$ from reaching $$$(\alpha+1,\beta-1)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-822027 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822027 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822027"> <li> <div class="comment"> <table class="comment-table" commentId="822370" commentParentId="822027"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 13:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822370" href="?#comment-822370" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822027" style="font-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="822370" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="822370" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822370"> <div class="moveup"> <div class="ttypography"><p>Thanks for amz explain. I realize that I had some missunderstand in the way we calc $$$P(reach\ A\ before\ B)$$$</p><p>This's exactly what in my mind one day ago: let $$$s = ...a...b...$$$ where $$$a$$$ and $$$b$$$ is node $$$a$$$ and node $$$b$$$, &quot;$$$...$$$&quot; mean some node between them which we chose them in exactly that order, or in other word, $$$s$$$ is state represent what we chose (exact in this order) I think $$$P(reach\ A\ before\ B)$$$ (or $$$P(A&lt;B)$$$) must be calculate in this way :</p><p>$$$P(A&lt;B) = \sum_{\substack{all\ s\ which\ a&lt;b}} P(s)$$$</p><p>But unfortunately, it's wrong (may be, or I still missunderstanding)</p><p>$$$P(A) = \sum_{\substack{all\ B[i]\ \subseteq\ A}} P(B[i])$$$ if and only if all $$$B[i]$$$ are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-822370 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822370 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822370"> <li> <div class="comment"> <table class="comment-table" commentId="822755" commentParentId="822370"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 22:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822755" href="?#comment-822755" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822370" style="font-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="822755" 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="822755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822755"> <div class="moveup"> <div class="ttypography"><p>$$$P(A &lt; B)$$$ in your terms is exactly what we need (if a = A and b = B).</p><p>I don't understand last formula, everything else looks fine.</p><p>And to find $$$P(A &lt; B)$$$ we use fact above and calculate all possible ways to reach $$$a$$$ earlier than $$$b$$$ we use $$$(\alpha, \beta)$$$ states using my notation: you either get $$$\alpha$$$ equal to dist to $$$a$$$ when $$$\beta$$$ = 0, or $$$\beta$$$ = 1, or 2, or 3...</p> <center>$$$ P(A &lt; B) = \\ =\sum\limits_{i=0}^{dist(b,l)}P(reach(dist(a,l),i)\;given\; reached(dist(a,l)-1,i)) \\ = \sum\limits_{i=0}^{dist(b,l)}P(reached(dist(a,l)-1,i))\cdot \frac{1}{2} $$$</center><p>Or you can rephrase task into other task with two kind of balls. What probability to remove all balls of one kind earlier than other, if you pick one or other kind of ball with probability 1/2.</p></div> </div> </div> <div class="reply info"> <a class="comment-822755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822755"> </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="808983" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/xsc" style="position: relative;"> <img src='https://userpic.codeforces.org/343/avatar/9eaf243b1eb8c3d4.jpg'/> </a> <div><a href="/profile/xsc" title="Specialist xsc" class="rated-user user-cyan">xsc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808983" href="?#comment-808983" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808983" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="343" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808983"> <div class="moveup"> <div class="ttypography"><p>Div2 D, O(N^4) solution <a href="/contest/1541/submission/120623566" title="Посылка 120623566 от xsc">120623566</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808983 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808983 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808983"> <li> <div class="comment"> <table class="comment-table" commentId="809278" commentParentId="808983"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DavidXu_JJ" style="position: relative;"> <img src='https://userpic.codeforces.org/2003708/avatar/623dc8036b4e9d72.jpg'/> </a> <div><a href="/profile/DavidXu_JJ" title="Expert DavidXu_JJ" class="rated-user user-blue">DavidXu_JJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809278" href="?#comment-809278" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808983" style="font-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="809278" 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="809278" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2003708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809278"> <div class="moveup"> <div class="ttypography"><p>Your code really helps me a lot in debugging,thanks.</p><p>By the way,it's weired that I get Wrong6 when I try to optimize to O(N^3*logN) by binary search on tree.</p><p>I have tested my function on other online judge and my function seems to be correct.</p></div> </div> </div> <div class="reply info"> <a class="comment-809278 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809278 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809278"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809018" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ducati" style="position: relative;"> <img src='https://userpic.codeforces.org/699102/avatar/eff3c352646e914e.jpg'/> </a> <div><a href="/profile/ducati" title="Grandmaster ducati" class="rated-user user-red">ducati</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 03:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809018" href="?#comment-809018" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809018" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="699102" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809018"> <div class="moveup"> <div class="ttypography"><p>Although Div.2 D is harder than ever, in my opinion, it's such a useful and excellent problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-809018 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809018 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809018"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809046" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KanishkGoel" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/KanishkGoel" title="Expert KanishkGoel" class="rated-user user-blue">KanishkGoel</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809046" href="?#comment-809046" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809046" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1917239" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809046"> <div class="moveup"> <div class="ttypography"><p>Is it usual for people to post solutions online during the contest like this channel? <a href="https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ">https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809046 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809046 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809046"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809051" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809051" href="?#comment-809051" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809051"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain why this submission <a href="/contest/1541/submission/120562335" title="Посылка 120562335 от Karnania7201">120562335</a> is failing for Div2 B? It would be a great help.</p></div> </div> </div> <div class="reply info"> <a class="comment-809051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809051"> <li> <div class="comment"> <table class="comment-table" commentId="809076" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809076" href="?#comment-809076" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809076" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809076"> <div class="moveup"> <div class="ttypography"><p>Bro you did not included the condition that i and j should be different i.e (i != j) because it is given in question that no are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-809076 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809076 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809076"> <li> <div class="comment"> <table class="comment-table" commentId="809079" commentParentId="809076"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:08">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809079" href="?#comment-809079" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809076" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809079" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809079"> <div class="moveup"> <div class="ttypography"><p>I think its covered as I started j from i+1. I tried that explicitly too but it didn't work. I wrote the same idea in a different way and it worked but this kind of implementation is not working.</p></div> </div> </div> <div class="reply info"> <a class="comment-809079 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809079 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809079"> <li> <div class="comment"> <table class="comment-table" commentId="809082" commentParentId="809079"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809082" href="?#comment-809082" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809079" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809082" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809082"> <div class="moveup"> <div class="ttypography"><p>yeah, you are right, I run your code using vector instead of creating memeset it worked fine, i guess there is some problem in that. <a href="https://codeforces.com/contest/1541/submission/120633207">120633207</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809082 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809082 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809082"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809081" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_NICkk" style="position: relative;"> <img src='https://userpic.codeforces.org/1543175/avatar/6084dd87f2c1cad9.jpg'/> </a> <div><a href="/profile/_NICkk" title="Expert _NICkk" class="rated-user user-blue">_NICkk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809081" href="?#comment-809081" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809081" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1543175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809081"> <div class="moveup"> <div class="ttypography"><p>Only fault in your code is that you didn't used memset correctly </p><p>I just changed your memset with this &quot; memset(ind, 0, sizeof(ind)) &quot; and it worked perfectly fine</p></div> </div> </div> <div class="reply info"> <a class="comment-809081 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809081 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809081"> <li> <div class="comment"> <table class="comment-table" commentId="809091" commentParentId="809081"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:37">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809091" href="?#comment-809091" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809081" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809091" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809091"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot to both of you. I shouldn't have used it without properly knowing about it. </p></div> </div> </div> <div class="reply info"> <a class="comment-809091 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809091 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809091"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809064" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vrintle" style="position: relative;"> <img src='https://userpic.codeforces.org/1991777/avatar/24d9007095afbbb6.jpg'/> </a> <div><a href="/profile/vrintle" title="Master vrintle" class="rated-user user-orange">vrintle</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809064" href="?#comment-809064" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809064" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1991777" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809064"> <div class="moveup"> <div class="ttypography"><p>Instead of $$$a_i \cdot a_j \leq 2n$$$, we could also check $$$a_i \cdot a_j \leq i+n$$$ which is a bit faster ($$$ \sim 62ms$$$).</p></div> </div> </div> <div class="reply info"> <a class="comment-809064 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809064 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809064"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809066" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809066" href="?#comment-809066" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809066" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809066"> <div class="moveup"> <div class="ttypography"><p>can anyone explain B. pleasant pairs more easy words?? </p></div> </div> </div> <div class="reply info"> <a class="comment-809066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809066"> <li> <div class="comment"> <table class="comment-table" commentId="809067" commentParentId="809066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809067" href="?#comment-809067" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809067" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809067"> <div class="moveup"> <div class="ttypography"><p>And also what is ask in 3rd question i cant understand what asked in it</p></div> </div> </div> <div class="reply info"> <a class="comment-809067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809067"> <li> <div class="comment"> <table class="comment-table" commentId="809070" commentParentId="809067"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809070" href="?#comment-809070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809067" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809070"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">https://www.youtube.com/watch?v=xCj_ZR5kENo</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809098" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809098" href="?#comment-809098" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809098" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809098"> <div class="moveup"> <div class="ttypography"><p>For those who are searching for a simple solution for great Graphs problems in O (nlogn). <a href="https://codeforces.com/contest/1541/submission/120600816">https://codeforces.com/contest/1541/submission/120600816</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809098 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809098 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809098"> <li> <div class="comment"> <table class="comment-table" commentId="809119" commentParentId="809098"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fjvzr" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/fjvzr" title="Newbie fjvzr" class="rated-user user-gray">fjvzr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809119" href="?#comment-809119" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809098" style="font-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="809119" 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="809119" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1623986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809119"> <div class="moveup"> <div class="ttypography"><p>Bro can u explain this soln????? i thought of taking all pairs that give negative edges except for the adjacent pairs.... bt getting wrong ans in 3rd 4th test case.....</p><p>while(n&gt;2) { sum-=(n-2)*(llabs(a[j]-a[i])); n--; // n = size i++; // i = 0 j--; // j = n-1 } cout&lt;&lt;sum&lt;&lt;endl;</p><p><a href="https://codeforces.com/contest/1541/submission/120636509">mysoln</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809119 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809119 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809119"> <li> <div class="comment"> <table class="comment-table" commentId="809124" commentParentId="809119"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809124" href="?#comment-809124" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809119" style="font-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="809124" 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="809124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809124"> <div class="moveup"> <div class="ttypography"><p>My solution is simple. First sort the array. </p><p>Then start connecting adjacent values with their differences. This way sum of all edges with positive weight will be same as the sum of adjacent differences in the array.</p><p>After that start making negative edges for every i. So each i will have i negative edges. Where negative weight is same as -(arr[i] — arr[j]).</p><p>Instead of search it for every j I have formula as (prefixsum till i) — arr[i]*i</p></div> </div> </div> <div class="reply info"> <a class="comment-809124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809124"> <li> <div class="comment"> <table class="comment-table" commentId="809132" commentParentId="809124"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809132" href="?#comment-809132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809124" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809132"> <div class="moveup"> <div class="ttypography"><p>can you tell me why are we sorting the array for a particular node call it x we need to add a negative weight from x to 1 , x to 2 x to 3 till x to x-1 keeping in mind the the path sum doesn't become negative so why are we sorting the array</p></div> </div> </div> <div class="reply info"> <a class="comment-809132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809132"> <li> <div class="comment"> <table class="comment-table" commentId="809135" commentParentId="809132"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809135" href="?#comment-809135" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809135" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809135"> <div class="moveup"> <div class="ttypography"><p>We are sorting values only once so as to connect neighboring nodes with minimum values,i.e. difference b/w consecutive values.<br /> From this sum of positive edges will be minimum.</p></div> </div> </div> <div class="reply info"> <a class="comment-809135 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809135 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809135"> <li> <div class="comment"> <table class="comment-table" commentId="809139" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809139" href="?#comment-809139" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809139" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809139"> <div class="moveup"> <div class="ttypography"><p>ohhh thanks I got it</p></div> </div> </div> <div class="reply info"> <a class="comment-809139 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809139 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809139"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809145" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809145" href="?#comment-809145" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809145" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809145"> <div class="moveup"> <div class="ttypography"><p>My solution is working now I only needed to sort the array my code would have been accepted during the contest :(</p></div> </div> </div> <div class="reply info"> <a class="comment-809145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809145"> </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="809116" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ken_KaNeKi_997" style="position: relative;"> <img src='https://userpic.codeforces.org/1737228/avatar/50ceb845253df5d4.jpg'/> </a> <div><a href="/profile/Ken_KaNeKi_997" title="Newbie Ken_KaNeKi_997" class="rated-user user-gray">Ken_KaNeKi_997</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809116" href="?#comment-809116" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809116" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1737228" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809116"> <div class="moveup"> <div class="ttypography"><p>can anyone explain div2 B plz</p></div> </div> </div> <div class="reply info"> <a class="comment-809116 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809116 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809116"> <li> <div class="comment"> <table class="comment-table" commentId="809204" commentParentId="809116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809204" href="?#comment-809204" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809116" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809204" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809204"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/92199#comment-809178">here</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809204 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809204 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809204"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809122" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809122" href="?#comment-809122" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809122" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809122"> <div class="moveup"> <div class="ttypography"><p>Beautiful Problems. Amazing Round!!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-809122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809122"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809156" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dummybawa" style="position: relative;"> <img src='https://userpic.codeforces.org/1704408/avatar/1522f670cd21321.jpg'/> </a> <div><a href="/profile/dummybawa" title="Expert dummybawa" class="rated-user user-blue">dummybawa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809156" href="?#comment-809156" style="font-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="809156" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809156" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1704408" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809156"> <div class="moveup"> <div class="ttypography"><p>UPD: It's wrong. </p></div> </div> </div> <div class="reply info"> <a class="comment-809156 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809156 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809156"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809178" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809178" href="?#comment-809178" style="font-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="809178" 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="809178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809178"> <div class="moveup"> <div class="ttypography"><p>For DIV 2C/1A can anyone explain with this test case N = 6 and D = 0 1 2 3 2 3. What are the edges that we can have with their weights?</p></div> </div> </div> <div class="reply info"> <a class="comment-809178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809178"> <li> <div class="comment"> <table class="comment-table" commentId="809198" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Zemrith" style="position: relative;"> <img src='https://userpic.codeforces.org/1159882/avatar/2a6566e372882267.jpg'/> </a> <div><a href="/profile/Zemrith" title="Expert Zemrith" class="rated-user user-blue">Zemrith</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809198" href="?#comment-809198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-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="809198" 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="809198" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159882" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809198"> <div class="moveup"> <div class="ttypography"><p>Hello! The answer would be -18.</p><p>Diagram: <img alt=" " src="/predownloaded/8c/88/8c88a0230dea9f499896ee59def659611c605976.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Notice that once you sort the distances, the adjacent nodes have no effect on your final answer. But you can add negative edges as long as they are not adjacent, resulting in such a diagram. Hence you can use prefix sums to solve the problem. (if x nodes came before this, for each node, the answer to add is (x-1)*curr value — csum of first (x-1) nodes). </p><p>Hope that made sense!</p></div> </div> </div> <div class="reply info"> <a class="comment-809198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809198"> <li> <div class="comment"> <table class="comment-table" commentId="809218" commentParentId="809198"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:27">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809218" href="?#comment-809218" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809218" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809218"> <div class="moveup"> <div class="ttypography"><p>Thank you <a class="rated-user user-cyan" href="/profile/Zemrith" title="Специалист Zemrith">Zemrith</a> for so much detail explanation and the solution too it helped me a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-809218 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809218 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809218"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809199" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809199" href="?#comment-809199" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809199" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809199"> <div class="moveup"> <div class="ttypography"><p>first sort the array they will from non negative weight edges. 0 -&gt; 1 -&gt; 2 -&gt; 2 -&gt; 3 -&gt; 3 so the non negative weights will be 1 | 1 | 0 | 1 | 0. form here greedily build most negative weights(backward edges) such that there are no negative cycles.</p></div> </div> </div> <div class="reply info"> <a class="comment-809199 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809199 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809199"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809203" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809203" href="?#comment-809203" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809203" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809203"> <div class="moveup"> <div class="ttypography"><p>First you can sort D and get: <code> N = 6, D = [0, 1, 2, 2, 3, 3] </code></p><p>Now calculate the diffs:</p><p><code>diffs = [1, 1, 0, 1, 0]</code></p><p>The edges for this graph could be something like this:</p> <pre><code> 1 1 0 1 0 &lt;- forward edges 1 &lt;-&gt; 2 &lt;-&gt; 3 &lt;-&gt; 4 &lt;-&gt; 5 &lt;-&gt; 6 -1 -1 0 -1 0 &lt;- backward edges </code></pre><p>Now you have to add more negatives edges, and you could do this by choosing some <code>i</code> and <code>j</code>, <code>i &lt; j</code> and add an edges from <code>j</code> to <code>i</code>, and the weight will be sum of the values from <code>diff[i]</code> to <code>diff[j]</code>.</p><p>Another way to think about this is: look at <code>D</code> array, it represents distances between adjacent nodes, all we have to do is add all of the edges with length 2, then all of the edges of length 3, ..., all of the edges of length <code>N - 1</code>.</p><p>So, for our case we would have these edges</p> <pre><code>a b W ------- 1 2 - 1 2 3 - 1 3 4 - 0 &lt;- adjacent forward edges 4 5 - 1 5 6 - 0 2 1 - -1 3 2 - -1 4 3 - 0 &lt;- adjacent backward edges 5 4 - -1 6 5 - 0 3 1 - -2 4 2 - -1 5 3 - -1 &lt;- edges of length 2 6 4 - -1 4 1 - -2 5 2 - -2 &lt;- edges of length 3 6 3 - -1 5 1 - -3 6 2 - -2 &lt;- edges of length 4 6 1 - -3 &lt;- edges of length 5 </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809203 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809203 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809203"> <li> <div class="comment"> <table class="comment-table" commentId="809221" commentParentId="809203"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809221" href="?#comment-809221" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809203" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809221" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809221"> <div class="moveup"> <div class="ttypography"><p>Thank You <a class="rated-user user-green" href="/profile/ilidar" title="Ученик ilidar">ilidar</a> for clearing my doubt and for detailed explaination.</p></div> </div> </div> <div class="reply info"> <a class="comment-809221 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809221 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809221"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809280" href="?#comment-809280" style="font-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="809280" revisionCount="7" revision="7"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">7</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809280" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+18</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809280"> <div class="moveup"> <div class="ttypography"><p>Could someone please provide a more strict intuition or insight of Div2D/Div1B of why &quot;the actual probability p does not matter&quot;? The intuition in the editorial is still alien to me of why those choices of not progess toward to either stacks (and probability 'p' also changes from time to time too) doesn't matter.</p><p>Update: Here is the intuition I came up with (The strict proof can be found in the comment of the author below)</p><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left) in some states of the current tree.</p><p>now, we will try break this $$$dp_{i,j}$$$ down into the sum of $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$</p><p>We will try to illustrate this with trying to split and color, either red or blue, a stick of length $$$1$$$. The length of the sticks representing the 'probability', and the color of the sticks will represent $$$dp_{i-1,j}$$$(red) or $$$dp_{i,j-1}$$$(blue), depending on the color.</p><p>Suppose in the current state, we have probability $$$p$$$ for choosing to pop each stacks, and the rest $$$1-2p$$$ of doing nothing. The picture will look like this:</p><p><a href="https://ibb.co/q9HjQTm"><img alt="Tree-Array-Rep" border="0" src="/predownloaded/13/57/135732d2b0967af0f76c1dba28df72086f234c7d.png" style="max-width: 100.0%;max-height: 100.0%;" /></a></p><p>We will split the stick equally(*) into several sticks of length $$$p$$$, and then color two of them red and blue. (* We can split it evenly because in the original problem, $$$p$$$ is in the form $$$\frac{1}{number\ of\ candidate\ unmark\ nodes}$$$ ) Now, the remaining sticks represent the state of $$$dp_{i,j}$$$ again (in some other state of the entire tree, so might be in some different $$$p$$$). That means we will split those sticks similary.</p><p>The key observations is:</p><p>1) We know that, in the original problem, if we keep picking nodes that aren't progressing toward the target nodes, we will run out of nodes eventually and finally choose the two nodes. That means, all the sticks will eventually colored into 'red' and 'blue'.</p><p>2) When we split a stick into several smaller equal length sticks, we will color two of them into red and blue. <strong>Those two sticks always have the same length</strong>. That means, the total length of blue sticks and the total length of red sticks will be equal in the end.</p><p>Analogically, that means, eventually, $$$dp_{i,j}$$$ will split into $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$ evenly, no matter $$$p$$$ might be or the state of tree of $$$dp_{i,j}$$$ might be. Therefore, $$$dp_{i,j} = \frac{1}{2} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-809280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809280"> <li> <div class="comment"> <table class="comment-table" commentId="809284" commentParentId="809280"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809284" href="?#comment-809284" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809280" style="font-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="809284" 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="809284" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809284"> <div class="moveup"> <div class="ttypography"><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left), with having arbitary probability $$$0 &lt; p \leq 0.5$$$ of chosing to pick the top of each stack (and $$$1-2p$$$ for doing nothing). Then</p><p>$$$dp_{i,j}=\int_{0}^{0.5} x \cdot (dp_{i-1,j}+dp_{i,j-1}) + (1-2x) \cdot dp_{i,j} \,dx$$$</p><p>Solving the equation, we get $$$dp_{i,j}=\frac{1}{6} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$ What is the mistake in this logic?</p></div> </div> </div> <div class="reply info"> <a class="comment-809284 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809284 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809284"> <li> <div class="comment"> <table class="comment-table" commentId="809399" commentParentId="809284"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809399" href="?#comment-809399" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809284" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809399" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809399"> <div class="moveup"> <div class="ttypography"><p>The biggest issue with this logic is that it's assuming $$$p$$$ is arbitrary chosen from a certain state. While $$$p$$$ can be anything in the world, it is always an exact number from a certain state, hence why an integral is wrong. </p><p>As a different type of intuition, you can think, &quot;is it more likely to reach $$$(i-1, j)$$$ than state $$$(i, j-1)$$$&quot;? and vice versa. For me at least, I don't see how it's possible for either of those questions to be true, so they should be equal.</p><p>If you're looking for a more rigorously correct $$$dp$$$, it would look something like this.</p> <div class="spoiler"><b class="spoiler-title">Proof</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp_{i, j, S}$$$ denote the probability of reaching some node $$$i$$$ distance away before some node $$$j$$$ distance away where $$$S$$$ is a representation of the entire state of of the process (not necessarily an integer). I think you already understood why we can assume the $$$lca$$$ is already reached. We aim to show that $$$S$$$ does not matter in our calculation. Assume inductively that $$$S$$$ does not matter. So, we can assume that states $$$(i-1, j)$$$ and states $$$(i, j-1)$$$ are irrelevant to $$$S$$$. Hence, the part we need to care about is $$$(1-2p) dp_{i, j, S \rightarrow S_a}$$$. A way of thinking about this part of the transition is moving through the collection of $$$S$$$ with the state $$$(i, j)$$$. Obviously, the $$$dp$$$ is a $$$DAG$$$ because no state $$$S$$$ can reach another. Each bounce takes a certain probability $$$p$$$ which is just multiplied in the current path. So, for each state $$$S$$$ with state $$$(i, j)$$$, we have a certain probability to reach it by simply calculating $$$dp$$$ along a DAG as is traditional. Then, from those states of $$$(i, j)$$$ you transition to $$$(i, j-1)$$$ with an equal probability $$$(i-1, j)$$$. So, they have to be equal. Finally, this argument holds for any initial state $$$S$$$ that you reach, so we can conclude that, from any state $$$S$$$ with a state of $$$(i, j)$$$, the probability of transitions to $$$(i-1, j)$$$ and $$$(i, j-1)$$$ are always exactly $$$0.5$$$.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-809399 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809399 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809399"> <li> <div class="comment"> <table class="comment-table" commentId="809701" commentParentId="809399"> <tr> <td class="left"> <div style="position: absolute; left: 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/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809701" href="?#comment-809701" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809399" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809701" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809701"> <div class="moveup"> <div class="ttypography"><p>I see, thank you so much!</p></div> </div> </div> <div class="reply info"> <a class="comment-809701 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809701 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809701"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809298" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/satyam_singh93" style="position: relative;"> <img src='https://userpic.codeforces.org/1763011/avatar/9d9fa405de19ab0e.jpg'/> </a> <div><a href="/profile/satyam_singh93" title="Newbie satyam_singh93" class="rated-user user-gray">satyam_singh93</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809298" href="?#comment-809298" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809298" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1763011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809298"> <div class="moveup"> <div class="ttypography"><p>I am getting wrong ans . could someone tell me where the code make differene ( [yestrday competiton problem .</p><p>`](<a href="https://codeforces.com/contest/1541/problem/B)">https://codeforces.com/contest/1541/problem/B)</a>.</p> <pre><code>int main( ) { clock_t begin = clock(); file_i_o(); // Write your code here.... int t; cin&gt;&gt;t; while(t-- ){ int n; cin&gt;&gt;n; vector&lt;pair&lt;int,int&gt;&gt;v; v.push_back({0,0}); loop(i,0,n) { int x; cin&gt;&gt;x; v.pb({x,i+1}); } sort(v.begin()+1,v.end()); int count =0; for(int i=1 ; i&lt;=n;i++) { for(ll j=i+1;j&lt;=n;j++) { ll left = v[i].first * v[j].first; ll right = v[i].second + v[j].second; if(left == right) count++; if(left &gt; 2*n ) break; } } cout&lt;&lt;count&lt;&lt;endl; } </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809298 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809298 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809298"> <li> <div class="comment"> <table class="comment-table" commentId="809305" commentParentId="809298"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809305" href="?#comment-809305" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809298" style="font-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="809305" 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="809305" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809305"> <div class="moveup"> <div class="ttypography"><p>v[i].first * v[j].first can create overflow. So, you need to convert them to long long by using</p><p>ll left = 1LL * v[i].first * v[j].first;</p><p>instead and it would pass.</p><p>(Simply save the value in long long won't help. You need to convert them to long long before doing multiplication. 1LL* is one way)</p></div> </div> </div> <div class="reply info"> <a class="comment-809305 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809305 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809305"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809309" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809309" href="?#comment-809309" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809309" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809309"> <div class="moveup"> <div class="ttypography"><p>Hi, in problem Div1.B/Div2.D; I can't wrap my head around $$$F[x][y]=F[x−1][y]/2+F[x][y−1]/2$$$. Why is it not $$$F[x][y]=F[x−1][y+1]/2+F[x+1][y−1]/2$$$, can someone please explain to me why is my transition wrong and/or why is the aforementioned transition correct? </p></div> </div> </div> <div class="reply info"> <a class="comment-809309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809309"> <li> <div class="comment"> <table class="comment-table" commentId="809311" commentParentId="809309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809311" href="?#comment-809311" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809311" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809311"> <div class="moveup"> <div class="ttypography"><p>x and y is the distance left for each side right? So, if you take one out, it won't make sense to add that one to the other side since the distance should be either x-1 and y or x and y-1.</p></div> </div> </div> <div class="reply info"> <a class="comment-809311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809311"> <li> <div class="comment"> <table class="comment-table" commentId="809339" commentParentId="809311"> <tr> <td class="left"> <div style="position: absolute; left: 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/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809339" href="?#comment-809339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809339" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809339"> <div class="moveup"> <div class="ttypography"><p>Thank you so much I understand. I had a minor misunderstanding of the parameters to the dp state.</p></div> </div> </div> <div class="reply info"> <a class="comment-809339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809339"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809371" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:13">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809371" href="?#comment-809371" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809371" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809371"> <div class="moveup"> <div class="ttypography"><p>PLease explain why 2 same codes are not giving the same ans</p><p>code forces round 728 div2<br />Problem B :<a href="https://codeforces.com/contest/1541/problem/B">https://codeforces.com/contest/1541/problem/B</a></p><p>AC Submission : <a href="https://ide.codingblocks.com/s/579769">https://ide.codingblocks.com/s/579769</a></p><p>Wrong output Submission :<a href="https://ide.codingblocks.com/s/579771">https://ide.codingblocks.com/s/579771</a></p><p>Difference is using of macro (node) instead of pair&lt;int,int&gt; </p><p>Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-809371 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809371 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809371"> <li> <div class="comment"> <table class="comment-table" commentId="809379" commentParentId="809371"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809379" href="?#comment-809379" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809371" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809379" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809379"> <div class="moveup"> <div class="ttypography"><p>If i am using #define node pair&lt;int,int&gt; it is getting accepted but when i am using typedef pair&lt;int,int&gt; node; it is giving wrong answer</p><p>Why this is happening ?? Is it a bug??</p></div> </div> </div> <div class="reply info"> <a class="comment-809379 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809379 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809379"> <li> <div class="comment"> <table class="comment-table" commentId="809407" commentParentId="809379"> <tr> <td class="left"> <div style="position: absolute; left: 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/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 19:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809407" href="?#comment-809407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809379" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809407" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809407"> <div class="moveup"> <div class="ttypography"><p>Not really sure why this is happening.</p><p>However, I think the problem is the position of #define int long long. So, for #define pair&lt;int,int&gt; node it seems that compiler change node -&gt; pair&lt;int,int&gt; -&gt; pair&lt;long long, long long&gt;. However, when you do typedef, it still keeps in pair&lt;int, int&gt; which creates an overflow problem later on. </p><p>I did try moving #define int long long up above typedef and the code pass. So, my best guess is #define int long long only replace int after that position with long long. Thus, node is still pair&lt;int, int&gt; in the typedef solution, while node is changed to pair&lt;long long, long long&gt; in the second solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-809407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809407"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809627" href="?#comment-809627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809627"> <div class="moveup"> <div class="ttypography"><p>May I ask why in the Div1D solution ci=i-bi, I think it should be ci=bi ...</p></div> </div> </div> <div class="reply info"> <a class="comment-809627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809627"> <li> <div class="comment"> <table class="comment-table" commentId="809631" commentParentId="809627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809631" href="?#comment-809631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809631" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809631"> <div class="moveup"> <div class="ttypography"><p>Check the definition of bi again dude. bi here means <strong>number of elements greater than pi</strong>. So to get ci, which is <strong>number of elements smaller than pi</strong>, you need i-bi.</p></div> </div> </div> <div class="reply info"> <a class="comment-809631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809631"> <li> <div class="comment"> <table class="comment-table" commentId="809636" commentParentId="809631"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809636" href="?#comment-809636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809636"> <div class="moveup"> <div class="ttypography"><p>I read it again. If I read it correctly, bi stands for j&lt;i,pj&gt;pi, and ci stands for j&gt;i,pj&lt;pi. For example, p={1,3,5,4,6,2}, I think b4=1,c4=1, please point out my problem</p></div> </div> </div> <div class="reply info"> <a class="comment-809636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809636"> <li> <div class="comment"> <table class="comment-table" commentId="809638" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809638" href="?#comment-809638" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809638" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809638"> <div class="moveup"> <div class="ttypography"><p>oh, the array index starts from 1</p></div> </div> </div> <div class="reply info"> <a class="comment-809638 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809638 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809638"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809639" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809639" href="?#comment-809639" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809639" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809639"> <div class="moveup"> <div class="ttypography"><p>You are right.</p><p>I guess it might just be typo and ci stands for j&lt;i, pj&lt;pi. At least with this definition of ci the algorithm seems correct :)</p></div> </div> </div> <div class="reply info"> <a class="comment-809639 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809639 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809639"> <li> <div class="comment"> <table class="comment-table" commentId="809641" commentParentId="809639"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809641" href="?#comment-809641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809639" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809641"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-809641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809641"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809705" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/darthrevenge" style="position: relative;"> <img src='https://userpic.codeforces.org/1567000/avatar/ee31d2a91a9575b9.jpg'/> </a> <div><a href="/profile/darthrevenge" title="Candidate Master darthrevenge" class="rated-user user-violet">darthrevenge</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809705" href="?#comment-809705" style="font-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="809705" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809705" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1567000" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809705"> <div class="moveup"> <div class="ttypography"><p>Here's my solution of B div 1 / D div 2 without LCA, using single DFS per node. <a href="/contest/1540/submission/120700765" title="Посылка 120700765 от darthrevenge">120700765</a> It is similar to what <a class="rated-user user-violet" href="/profile/OleschY" title="Кандидат в мастера OleschY">OleschY</a> suggested above. I've tried to describe it in the <a href="https://codeforces.com/blog/entry/92284">blog</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-809705 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809705 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809705"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809951" href="?#comment-809951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809951"> <div class="moveup"> <div class="ttypography"><p>Can someone explain how you can find the LCA for each pair so quick? Iterating through every root is and then considering every pair is already N^3</p></div> </div> </div> <div class="reply info"> <a class="comment-809951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809951"> <li> <div class="comment"> <table class="comment-table" commentId="809965" commentParentId="809951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PurpleCrayon" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809965" href="?#comment-809965" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809965" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="1604355" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809965"> <div class="moveup"> <div class="ttypography"><p>There are a couple ways you could do it:</p> <ol> <li>Just use standard binary lifting (initialize once for each root). This runs in $$$\mathcal{O}(n^3 \log{}n)$$$, and should pass under the given constraints. You could also just use $$$\mathcal{O}(1)$$$ lca using an rmq over an euler tour.</li> <li>You could use a version of dp, where $$$dp[a][b] = lca(a, b)$$$. If the depth of $$$a$$$ is greater than the depth of $$$b$$$, $$$dp[a][b] = dp[parent[a]][b]$$$, otherwise $$$dp[a][b] = dp[a][parent[b]]$$$. The base cases are $$$dp[a][a] = a$$$ for all $$$a$$$. This runs in $$$\mathcal{O}(n^3)$$$.</li> <li>You could extend this idea and do the main solution's dp directly on the tree (without ever worrying about lca's). The recurrence is equivalent to the main solution ($$$dp[a][b] = \frac{dp[parent[a]][b]+dp[a][parent[b]]}{2}$$$ with the base cases being one node is an ancestor of the other.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-809965 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809965 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809965"> <li> <div class="comment"> <table class="comment-table" commentId="809967" commentParentId="809965"> <tr> <td class="left"> <div style="position: absolute; left: 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/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809967" href="?#comment-809967" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809965" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809967" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809967"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the detailed answer!</p></div> </div> </div> <div class="reply info"> <a class="comment-809967 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809967 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809967"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="810320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Anurag_20" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Anurag_20" title="Specialist Anurag_20" class="rated-user user-cyan">Anurag_20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/30/2021 19:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810320" href="?#comment-810320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810320" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1600346" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810320"> <div class="moveup"> <div class="ttypography"><p>O(n2) is also working for div2 C Great Graphs. <a href="https://codeforces.com/contest/1540/submission/120964787">https://codeforces.com/contest/1540/submission/120964787</a></p></div> </div> </div> <div class="reply info"> <a class="comment-810320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810320"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="813828" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/T404" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/T404" title="Master T404" class="rated-user user-orange">T404</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/09/2021 19:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-813828" href="?#comment-813828" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="813828" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="523287" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-813828"> <div class="moveup"> <div class="ttypography"><p>Div1D can be done in $$$O(n \sqrt{n})$$$. We can use square root decomposition to replace all BITs in tutorial. Since a value in a non-updated position changes by at most one and all values change in the same direction, the full recomputation is only needed in the updated position and we can perform an incremental change in $$$O(1)$$$ for values in each non-updated positions.</p><p><a href="https://codeforces.com/contest/1540/submission/121831547">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-813828 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-813828 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-813828"> <li> <div class="comment"> <table class="comment-table" commentId="834051" commentParentId="813828"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KeyID" style="position: relative;"> <img src='https://userpic.codeforces.org/226684/avatar/10e3671716bf6859.jpg'/> </a> <div><a href="/profile/KeyID" title="Grandmaster KeyID" class="rated-user user-red">KeyID</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/29/2021 12:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-834051" href="?#comment-834051" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-813828" style="font-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="834051" 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="834051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="226684" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-834051"> <div class="moveup"> <div class="ttypography"><p>Realy impressive solution. I'm surprised no stars were given to you until me. Maybe many people didn't get your idea since the solution is actually much more complicated than your brief comment(at least in my opinion). I also wrote a piece of code which used your method but simplified a small part of steps. <a href="https://codeforces.com/contest/1540/submission/127317031">Here</a> it is.</p></div> </div> </div> <div class="reply info"> <a class="comment-834051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-834051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-834051"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="837924" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Harolinch" style="position: relative;"> <img src='https://userpic.codeforces.org/427341/avatar/cf8608aeb55edc95.jpg'/> </a> <div><a href="/profile/Harolinch" title="Pupil Harolinch" class="rated-user user-green">Harolinch</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837924" href="?#comment-837924" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837924" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="427341" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837924"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a> in problem Tree array you said that Fixing a given root r, the expected value of the entire process is obviously the sum of the expected values for a fixed root divided by n.</p><p>why we divide by n at the end ? </p></div> </div> </div> <div class="reply info"> <a class="comment-837924 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837924 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837924"> <li> <div class="comment"> <table class="comment-table" commentId="837928" commentParentId="837924"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837928" href="?#comment-837928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-837924" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837928" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837928"> <div class="moveup"> <div class="ttypography"><p>The calculation is independent based on whichever node that you choose first (it becomes the “root”). Initially you choose one of $$$n$$$ nodes with equal probability so you divide by $$$n$$$ at the end after you’ve summed up the independent expected value after choosing the node $$$i$$$ initially.</p></div> </div> </div> <div class="reply info"> <a class="comment-837928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837928"> </ul> </div> </li> </ul> </div> <br/> <div id="editBox-100805" 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 firstPreview100805 = true; var lastPreviewContent100805 = ''; 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=100805] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=100805] 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-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, 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:33:28</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:'81289372dffb0c4e',t:'MTY5NjcwNzIwOC45MzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1541B
1541
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$$$ <span class="tex-font-style-bf">различных</span> целых чисел. Посчитайте количество пар индексов $$$(i, j)$$$ таких, что $$$i &lt; j$$$ и $$$a_i \cdot a_j = i + j$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой стоке каждого набора задано одно целое число $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — длина массива $$$a$$$.</p><p>Во второй строке каждого набора заданы $$$n$$$ целых чисел через пробел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — массив $$$a$$$. Гарантируется, что все элементы массива <span class="tex-font-style-bf">различны</span>.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора выведите количество пар индексов $$$(i, j)$$$ таких, что $$$i &lt; j$$$ и $$$a_i \cdot a_j = i + j$$$.</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 1 3 6 1 5 5 3 1 5 9 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе единственная пара, удовлетворяющая условиям — это $$$(1, 2)$$$, так как $$$a_1 \cdot a_2 = 1 + 2 = 3$$$</p><p>Во втором наборе единственная подходящая пара – это $$$(2, 3)$$$.</p><p>В третьем наборе пары, удовлетворяющие условиям — это $$$(1, 2)$$$, $$$(1, 5)$$$ и $$$(2, 3)$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b454d10a7da1c5d1b4466c6b545d43b6"/> <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="3a2e30eec6604291efb1f3ef212d19e2d7715bd7"/> <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='b454d10a7da1c5d1b4466c6b545d43b6'>&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%2F1541%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='b454d10a7da1c5d1b4466c6b545d43b6'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1541">Codeforces Round 728 (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='b454d10a7da1c5d1b4466c6b545d43b6'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1541/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *1200 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b454d10a7da1c5d1b4466c6b545d43b6'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1027093"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b454d10a7da1c5d1b4466c6b545d43b6'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1027093"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92093" title="Codeforces Round #728" target="_blank">Codeforces Round #728 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13929" resourceName="Codeforces Round #728" resourceManual="true" src="//codeforces.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/92199" title="Tutorial" target="_blank">Tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13941" 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/1541">Задачи</a></li> <li><a href="/contest/1541/submit">Отослать</a></li> <li><a href="/contest/1541/my">Мои посылки</a></li> <li><a href="/contest/1541/status">Статус</a></li> <li><a href="/contest/1541/hacks">Взломы</a></li> <li><a href="/contest/1541/room/1">Комната</a></li> <li><a href="/contest/1541/standings">Положение</a></li> <li><a href="/contest/1541/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_3e043e58e0a0543290bea5963a1c881df4ac3c18"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ <span class="tex-font-style-bf">различных</span> целых чисел. Посчитайте количество пар индексов $$$(i, j)$$$ таких, что $$$i &lt; j$$$ и $$$a_i \cdot a_j = i + j$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой стоке каждого набора задано одно целое число $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — длина массива $$$a$$$.</p><p>Во второй строке каждого набора заданы $$$n$$$ целых чисел через пробел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot n$$$) — массив $$$a$$$. Гарантируется, что все элементы массива <span class="tex-font-style-bf">различны</span>.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора выведите количество пар индексов $$$(i, j)$$$ таких, что $$$i &lt; j$$$ и $$$a_i \cdot a_j = i + j$$$.</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 1 3 6 1 5 5 3 1 5 9 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе единственная пара, удовлетворяющая условиям — это $$$(1, 2)$$$, так как $$$a_1 \cdot a_2 = 1 + 2 = 3$$$</p><p>Во втором наборе единственная подходящая пара – это $$$(2, 3)$$$.</p><p>В третьем наборе пары, удовлетворяющие условиям — это $$$(1, 2)$$$, $$$(1, 5)$$$ и $$$(2, 3)$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c6fb790015ee',t:'MTY5NjY2NzM3NS45ODUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1200"]
https://codeforces.com/blog/entry/92199
<!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="ea33d124a1ff874ace73f937748d303e"/> <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="Codeforces Round #728 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #728 Editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='ea33d124a1ff874ace73f937748d303e'>&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%2F92199">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='ea33d124a1ff874ace73f937748d303e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:31:32</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:31:32</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='ea33d124a1ff874ace73f937748d303e'/> <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/PurpleCrayon">PurpleCrayon</a></li> <li class="current selectedLava"><a href="/blog/PurpleCrayon">Blog</a></li> <li><a href="/teams/with/PurpleCrayon">Teams</a></li> <li><a href="/submissions/PurpleCrayon">Submissions</a></li> <li><a href="/groups/with/PurpleCrayon">Groups</a></li> <li><a href="/contests/with/PurpleCrayon">Contests</a></li> <li><a href="/contests/writer/PurpleCrayon">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/PurpleCrayon" style="text-decoration:none;color:black !important;">PurpleCrayon's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="92809"> <div class="title"> <a href="/blog/entry/92199"> <p>Codeforces Round #728 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a>, <a href="/topic/92809/en10">history</a>, <span class="format-humantime" title="Jun/25/2021 20:44">2 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><a href="/contest/1541/problem/A" title="Codeforces Round 728 (Div. 2)">1541A - Pretty Permutations</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The parity (whether $$$n$$$ is odd or even) matters.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Swapping two adjacent cats keeps both of them close to their original location and changes both of their locations.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>If $$$n$$$ is even, the optimal distance is $$$n$$$, and if $$$n$$$ is odd the optimal distance is $$$n+1$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541A">Tutorial is loading...</div></div></div><p><a href="/contest/1541/problem/B" title="Codeforces Round 728 (Div. 2)">1541B - Pleasant Pairs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>$$$i+j \leq 2 \cdot n$$$</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The number of pairs $$$(a, b)$$$ such that $$$a \cdot b \leq x$$$ is $$$O(x log x)$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/A" title="Codeforces Round 728 (Div. 1)">1540A - Great Graphs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What's the minimum value that an edge from $$$a$$$ to $$$b$$$ can be?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use edges with negative value whenever you can.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The sum of the values of edges with positive weight must be $$$\geq$$$ the maximum value in the array.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540A">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Tree Array</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Fix the initial node chosen and root the tree there, what is the contribution of each pair of nodes?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Nothing matters besides the path from node $$$a$$$ to node $$$b$$$, and the initially chosen node $$$r$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>You are given two stacks of size $$$a_1$$$ and $$$a_2$$$. In a single step, you randomly choose a stack to remove a single item from. What is the probability that $$$a_1$$$ becomes $$$0$$$ before $$$a_2$$$? Can you extend this argument for an arbitrary probability $$$p$$$ to remove from one of the two stacks, and a probability of $$$1-2p$$$ to do nothing?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/C2" title="Codeforces Round 728 (Div. 1)">1540C2 - Converging Array (Hard Version)</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What are the invariants? The monovariants?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What is the prefix sum array of the converged array? What is the difference array of the converged array?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you conducted the process on a prefix of size $$$1$$$, then of size $$$2$$$, and on and on?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How many values $$$x$$$ are actually interesting?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540C2">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Inverse Inversions</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The answer is always unique.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Try to figure out what the location of the $$$i$$$-th element would be if you only looked at the first $$$i$$$ elements, then the first $$$i+1$$$, etc. to find an $$$O(nq)$$$ solution.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use sqrt decomposition to optimize it.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540D">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/E" title="Codeforces Round 728 (Div. 1)">1540E - Tasty Dishes</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How much does each chef's initial dish contribute at time $$$k$$$?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you really, really wanted to use matrix exponentiation?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How can you multiply some vectors by a matrix in $$$O(N)$$$ time? (go back to linear algebra class)</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Decompose into linear combinations of eigenvectors.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540E">Tutorial is loading...</div></div></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/1540" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 1)</a> </span> </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/1541" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-191295-92809").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "191295", blogEntryId: "92199", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-92809"><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'>+96</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-92809"><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/PurpleCrayon"><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/PurpleCrayon"> PurpleCrayon </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="Jun/25/2021 20:44">2 years ago</span> </li> <li> <a href="/blog/entry/92199#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/92199#comments"> 170 </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="100805"> <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 (136)</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="808750" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808750" href="?#comment-808750" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808750" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-66" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-66</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808750"> <div class="moveup"> <div class="ttypography"><p>PURPLECRAYON ORZ</p></div> </div> </div> <div class="reply info"> <a class="comment-808750 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808750 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808750"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808751" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hbarp" style="position: relative;"> <img src='https://userpic.codeforces.org/1387715/avatar/c727a810db6ffb66.jpg'/> </a> <div><a href="/profile/hbarp" title="Candidate Master hbarp" class="rated-user user-violet">hbarp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808751" href="?#comment-808751" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808751" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="1387715" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-83</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808751"> <div class="moveup"> <div class="ttypography"><p>Damn, so orz round. <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Мастер PurpleCrayon">PurpleCrayon</a> orz</p></div> </div> </div> <div class="reply info"> <a class="comment-808751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808751"> <li> <div class="comment"> <table class="comment-table" commentId="808805" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/naman1601" style="position: relative;"> <img src='https://userpic.codeforces.org/1703219/avatar/d63fc523dc05fda8.jpg'/> </a> <div><a href="/profile/naman1601" title="Master naman1601" class="rated-user user-orange">naman1601</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808805" href="?#comment-808805" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808805" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-51" data-commentUserId="1703219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-51</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808805"> <div class="moveup"> <div class="ttypography"><p>yeah, amazing problemset, not speedforces at all :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808805 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808805 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808805"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808817" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LOVELY_BOY_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/LOVELY_BOY_" title="Newbie LOVELY_BOY_" class="rated-user user-gray">LOVELY_BOY_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808817" href="?#comment-808817" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-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="808817" 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="808817" class="CommentVoteFrame" data-commentRating="35" data-commentUserId="2089809" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808817"> <div class="moveup"> <div class="ttypography"><p>LOL <a class="rated-user user-blue" href="/profile/hbarp" title="Эксперт hbarp">hbarp</a>,even you didn't participate in the contest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808817 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808817 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808817"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808753" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DontLookBack" style="position: relative;"> <img src='https://userpic.codeforces.org/1534766/avatar/4eacdc5f9758fc28.jpg'/> </a> <div><a href="/profile/DontLookBack" title="Specialist DontLookBack" class="rated-user user-cyan">DontLookBack</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808753" href="?#comment-808753" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808753" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1534766" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808753"> <div class="moveup"> <div class="ttypography"><p>I am curious, how many div2 testers solved D?</p></div> </div> </div> <div class="reply info"> <a class="comment-808753 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808753 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808753"> <li> <div class="comment"> <table class="comment-table" commentId="808826" commentParentId="808753"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/highonjuice" style="position: relative;"> <img src='https://userpic.codeforces.org/1457566/avatar/f7988dd2af03d38b.jpg'/> </a> <div><a href="/profile/highonjuice" title="Pupil highonjuice" class="rated-user user-green">highonjuice</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808826" href="?#comment-808826" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808753" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808826" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1457566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808826"> <div class="moveup"> <div class="ttypography"><p>like 2 ppl, it was hard for me</p></div> </div> </div> <div class="reply info"> <a class="comment-808826 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808826 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808826"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808757" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tlatoani" style="position: relative;"> <img src='https://userpic.codeforces.org/614001/avatar/598b4e8358aad1b4.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/Tlatoani" title="Grandmaster Tlatoani" class="rated-user user-red">Tlatoani</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:18">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808757" href="?#comment-808757" style="font-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="808757" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="808757" class="CommentVoteFrame" data-commentRating="121" data-commentUserId="614001" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+121</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808757"> <div class="moveup"> <div class="ttypography"><h4>Alternate solution to <a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Инвертируем инверсии</a></h4><p>(Read the first nontrivial paragraph of the editorial before reading this alternate solution)</p><p>Let $$$p_r(k) = x$$$ denote that of the numbers $$$p(1), \ldots, p(r)$$$ in sorted order, $$$p(k)$$$ is equal to the $$$x$$$th of these numbers. We will take a decomposition strategy just as the editorial does, though our strategy will be different. We will divide $$$[1, n]$$$ into blocks of length $$$b$$$. For each block covering some interval $$$[l, r]$$$, we will store $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>This means that for any $$$k$$$, if we know $$$p_r(k)$$$ for some block $$$[l, r]$$$, then we can determine $$$p_{r'}(k)$$$ for the block $$$[l', r']$$$ immediately to the right by binary searching on the numbers stored for $$$[l', r']$$$. Therefore, we can perform queries in $$$O\left(\frac n b \lg b\right)$$$.</p><p>We now need to figure out updates. There are probably simple ways to perform updates in $$$O(b\lg b)$$$, but this yields an overall runtime of $$$O(q\sqrt n \lg n)$$$ which is too slow.</p><p>Therefore, we can instead store each block as a segment tree. For each range $$$[l, r]$$$ in the segment tree we store the same thing we store for the whole block: $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>We then have to quickly merge two intervals. We can merge two intervals of length $$$\lambda$$$ in $$$O(\lambda \lg \lambda)$$$ by doing binary search just as we did above, but this still only yields $$$O(b\lg b)$$$ update overall. However, these $$$\lambda$$$ binary searches can be optimized using two pointers to $$$O(\lambda)$$$, making the overall update $$$O(b)$$$.</p><p>We thus have $$$O\left(\frac n b \lg b\right)$$$ query and $$$O(b)$$$ update. Therefore, we can choose $$$b = \sqrt{n\lg n}$$$ to attain an overall runtime of $$$O\left(q\sqrt{n\lg n}\right)$$$ just as the editorial does.</p><p><a href="https://codeforces.com/contest/1540/submission/120611645">Submission in Kotlin</a></p><p><a href="https://codeforces.com/contest/1540/submission/120612729">Submission in C++</a></p><p>It is interesting to note that this solution is quite fast. At the time of writing this update, the C++ version is the fastest correct submission (and runs under 1 second!) and the Kotlin version is faster than the vast majority of submissions.</p></div> </div> </div> <div class="reply info"> <a class="comment-808757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808757"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808765" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardcode229" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardcode229" title="Newbie hardcode229" class="rated-user user-gray">hardcode229</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808765" href="?#comment-808765" style="font-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="808765" 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="808765" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1635180" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808765"> <div class="moveup"> <div class="ttypography"><p>The 3rd hint for the second problem is same as that of the first problem, is it related or a mistake? <strong>UPD:</strong> it is corrected.</p></div> </div> </div> <div class="reply info"> <a class="comment-808765 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808765 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808765"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808769" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/peanut" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/peanut" title="Specialist peanut" class="rated-user user-cyan">peanut</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:24">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808769" href="?#comment-808769" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808769" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="1167233" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+22</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808769"> <div class="moveup"> <div class="ttypography"><p>speedforces.</p></div> </div> </div> <div class="reply info"> <a class="comment-808769 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808769 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808769"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808781" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/graphs_11" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/graphs_11" title="Specialist graphs_11" class="rated-user user-cyan">graphs_11</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808781" href="?#comment-808781" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808781" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1610110" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808781"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">Problem B Detailed Explanation</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808781 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808781 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808781"> <li> <div class="comment"> <table class="comment-table" commentId="809069" commentParentId="808781"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:40">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809069" href="?#comment-809069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808781" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809069" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809069"> <div class="moveup"> <div class="ttypography"><p>Thank you, very well explained</p></div> </div> </div> <div class="reply info"> <a class="comment-809069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809069"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808790" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PC_E1052" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PC_E1052" title="Pupil PC_E1052" class="rated-user user-green">PC_E1052</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808790" href="?#comment-808790" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808790" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="811219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808790"> <div class="moveup"> <div class="ttypography"><p>c was too easy, d was too hard. but d was very nice problem though. </p></div> </div> </div> <div class="reply info"> <a class="comment-808790 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808790 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808790"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808793" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808793" href="?#comment-808793" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808793" class="CommentVoteFrame" data-commentRating="58" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+58</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808793"> <div class="moveup"> <div class="ttypography"><p>Paging <a class="rated-user user-legendary" href="/profile/ecnerwala" title="Легендарный гроссмейстер ecnerwala"><span class="legendary-user-first-letter">e</span>cnerwala</a> to explain his solution to D1E if he'd like. It seems offline?</p></div> </div> </div> <div class="reply info"> <a class="comment-808793 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808793 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808793"> <li> <div class="comment"> <table class="comment-table" commentId="808979" commentParentId="808793"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ecnerwala" 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/ecnerwala" title="Legendary Grandmaster ecnerwala" class="rated-user user-legendary"><span class="legendary-user-first-letter">e</span>cnerwala</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808979" href="?#comment-808979" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808793" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808979" class="CommentVoteFrame" data-commentRating="40" data-commentUserId="57502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808979"> <div class="moveup"> <div class="ttypography"><p>My solution is $$$O(K N^3 + QN)$$$. I just precomputed the coefficient of each $$$a_i$$$ for each prefix-range for each number of days since person $$$i$$$ becomes positive (only $$$1000$$$ possible days) in $$$O(N \cdot K \cdot N^2)$$$, and then summed up the appropriate ones to answer each query in $$$O(N)$$$. It's written in the offline style to use only $$$O(KN)$$$ memory at a time (grouped by $$$a_i$$$) instead of $$$O(KN^2)$$$.</p><p>My passing submission is just $$$KN^3 / 6$$$ instead of the $$$KN^3$$$ I submitted in contest :'(</p><p>If you guys wanted to prevent this, $$$K$$$ could've been much higher, like $$$1e18$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808979 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808979 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808979"> <li> <div class="comment"> <table class="comment-table" commentId="809002" commentParentId="808979"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809002" href="?#comment-809002" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808979" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809002" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809002"> <div class="moveup"> <div class="ttypography"><p>:( I knew of this solution (it’s why ML is tight) but I didn’t realize that it could be done offline with small memory. Of course $$$K$$$ higher is obvious solution but main issue is that the extra modulos from binary exponentiation make it very hard to pass in Java without allowing other unoptimal solutions through such as precomputing inverses of the matrix. Probably $$$k=10^5$$$ would’ve been a better choice. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-809002 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809002 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809002"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808795" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zukonit14" style="position: relative;"> <img src='https://userpic.codeforces.org/1192187/avatar/5afd49be87fb87d9.jpg'/> </a> <div><a href="/profile/zukonit14" title="Expert zukonit14" class="rated-user user-blue">zukonit14</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808795" href="?#comment-808795" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808795" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1192187" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808795"> <div class="moveup"> <div class="ttypography"><p>Does Div2 D deserved to be D Problem? According to me it should've been Div2 E.</p></div> </div> </div> <div class="reply info"> <a class="comment-808795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808795"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808796" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mangat_angad" style="position: relative;"> <img src='https://userpic.codeforces.org/1449578/avatar/d3cadb0c26e0c11f.jpg'/> </a> <div><a href="/profile/mangat_angad" title="Specialist mangat_angad" class="rated-user user-cyan">mangat_angad</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808796" href="?#comment-808796" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808796" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1449578" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808796"> <div class="moveup"> <div class="ttypography"><p>I feel like such an idiot for not being able to understand problem C (Div2). For some reason I thought the nodes were connected like this — 1-&gt;2-&gt;3-&gt;....-&gt;N and that we had to minimise answer by adding other edges (of negative weight in case they dont give a negative cycle) to this graph.</p></div> </div> </div> <div class="reply info"> <a class="comment-808796 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808796 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808796"> <li> <div class="comment"> <table class="comment-table" commentId="808896" commentParentId="808796"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808896" href="?#comment-808896" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808796" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808896" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808896"> <div class="moveup"> <div class="ttypography"><p>But that's exactly what I did, and the final answer is the sum of the array — sum of all subarrays. <a href="https://codeforces.com/contest/1541/submission/120611950">120611950</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808896 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808896 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808896"> <li> <div class="comment"> <table class="comment-table" commentId="808941" commentParentId="808896"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808941" href="?#comment-808941" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808896" style="font-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="808941" 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="808941" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808941"> <div class="moveup"> <div class="ttypography"><p>No, that's not what you did. To compute the answer via the method described above, you would have to compute how many elements are lesser than the current element at any given iteration and add them and also keep and their count using a Fenwick tree/ BIT. That's the incorrect approach though because sorting would be more optimal.</p></div> </div> </div> <div class="reply info"> <a class="comment-808941 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808941 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808941"> <li> <div class="comment"> <table class="comment-table" commentId="808952" commentParentId="808941"> <tr> <td class="left"> <div style="position: absolute; left: 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/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808952" href="?#comment-808952" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808941" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808952" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808952"> <div class="moveup"> <div class="ttypography"><p>Sorry if I misunderstood things. mangat_angad only mentioned adding negative weighed edges to the 1-&gt;2-&gt;3-&gt;...N graph, which is what I thought to arrive at my solution. The array I mentioned is indeed sorted and formed by distance differences which are the weights in the 1-&gt;2-&gt;3-&gt;...N graph. Unfortunately I'm still too noob to understand the tree structures you mentioned.</p></div> </div> </div> <div class="reply info"> <a class="comment-808952 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808952 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808952"> <li> <div class="comment"> <table class="comment-table" commentId="808955" commentParentId="808952"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808955" href="?#comment-808955" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808952" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808955" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808955"> <div class="moveup"> <div class="ttypography"><p>Nothing unfortunate about it, logic trumps everything </p></div> </div> </div> <div class="reply info"> <a class="comment-808955 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808955 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808955"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808797" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808797" href="?#comment-808797" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808797" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808797"> <div class="moveup"> <div class="ttypography"><p>Just want to apologize to authors for the stupidest question, I misread the task..</p></div> </div> </div> <div class="reply info"> <a class="comment-808797 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808797 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808797"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808813" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808813" href="?#comment-808813" style="font-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="808813" 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="808813" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808813"> <div class="moveup"> <div class="ttypography"><p>Can someone tell me the meaning of this line in problem Div2D/Div1B<br /></p> <blockquote><p>Note that, until reaching, l every possible process still has the same probability of reaching b before a. Therefore, we can assume that the process has reached l and calculate the probability from there.</p> </blockquote><p>What same probability are they talking about?</p></div> </div> </div> <div class="reply info"> <a class="comment-808813 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808813 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808813"> <li> <div class="comment"> <table class="comment-table" commentId="808831" commentParentId="808813"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808831" href="?#comment-808831" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808813" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808831" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808831"> <div class="moveup"> <div class="ttypography"><p>Here's what it's trying to say:</p><p>Suppose we start by marking the root. To mark a or b, we must first mark the lca, so we may assume that the lca has just been marked.</p></div> </div> </div> <div class="reply info"> <a class="comment-808831 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808831 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808831"> <li> <div class="comment"> <table class="comment-table" commentId="808840" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808840" href="?#comment-808840" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808840" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808840"> <div class="moveup"> <div class="ttypography"><p>And what does this line mean? <em>&quot;The problem can be rephrased as having two stacks of size dist(l,a) and dist(l,b) with an arbitrary p to remove a node from one of the two stack (and 1−2p to nothing) and finding the probability that dist(l,b) reaches zero before dist(l,a).&quot;</em></p></div> </div> </div> <div class="reply info"> <a class="comment-808840 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808840 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808840"> <li> <div class="comment"> <table class="comment-table" commentId="808857" commentParentId="808840"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808857" href="?#comment-808857" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808840" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808857" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808857"> <div class="moveup"> <div class="ttypography"><p>Once you've reached the lca $$$l$$$, in a single step you either step closer to $$$a$$$, step closer to $$$b$$$, or step closer to neither.</p></div> </div> </div> <div class="reply info"> <a class="comment-808857 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808857 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808857"> <li> <div class="comment"> <table class="comment-table" commentId="808862" commentParentId="808857"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808862" href="?#comment-808862" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808857" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808862" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808862"> <div class="moveup"> <div class="ttypography"><p>Can you add implementation for this problem please?</p></div> </div> </div> <div class="reply info"> <a class="comment-808862 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808862 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808862"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808849" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808849" href="?#comment-808849" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808849" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808849"> <div class="moveup"> <div class="ttypography"><p>So, we mark lca first (of course). But why wouldn't it affect the final probability of reaching b before a? I mean, why is it sufficient to calculate the probability after marking lca?</p></div> </div> </div> <div class="reply info"> <a class="comment-808849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808849"> <li> <div class="comment"> <table class="comment-table" commentId="808873" commentParentId="808849"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808873" href="?#comment-808873" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808849" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808873" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808873"> <div class="moveup"> <div class="ttypography"><p>Before marking the lca, there is no way to make more progress towards $$$b$$$ than $$$a$$$ or vice versa. The subset of marked vertices also does not change the probability of moving towards $$$a$$$ or $$$b$$$ after reaching the lca because we're choosing uniformly at random and exactly two vertices are of interest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808873 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808873 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808873"> <li> <div class="comment"> <table class="comment-table" commentId="808883" commentParentId="808873"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808883" href="?#comment-808883" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808873" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808883" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808883"> <div class="moveup"> <div class="ttypography"><p>Now I get it. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808883 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808883 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808883"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808814" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808814" href="?#comment-808814" style="font-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="808814" 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="808814" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808814"> <div class="moveup"> <div class="ttypography"><p>So, my Solution for <strong>Div1 Problem B</strong> / <strong>Div2 Problem D</strong> / <strong>1540B — Tree Array</strong>:</p><p>Chose two Nodes $$$A$$$ and $$$B$$$ with $$$A&gt;B$$$. </p><p><strong>First DFS:</strong> Find the path from $$$A$$$ to $$$B$$$. I call it $$$path_p$$$. On $$$path_p$$$ mark the distance to $$$B$$$ for each node. </p><p><strong>Second DFS:</strong> For each remaining node $$$N$$$ find the shortest path to $$$path_p$$$. It will hit it at some node of the $$$path_p$$$ which has some distance $$$D$$$ marked on it. We mark $$$N$$$ with $$$D$$$. (See comment below for image.)</p><p><strong>Calculation:</strong> For each node $$$N$$$ we can calculate $$$P_i$$$. $$$P_i$$$ is the probability to reach Node $$$B$$$ before we reach Node $$$A$$$. We sum $$$P_i$$$ for each node. $$$P_i$$$ is also the probability, that the pair of Nodes $$$A$$$ and $$$B$$$ with starting node $$$N$$$ will contribute to the inversion sum. </p><p><strong>Iteration:</strong> We need to repeat this for each pair $$$A$$$ and $$$B$$$. In the end we divide the answer by $$$n$$$, the amount of nodes (the probability to start with Node $$$N$$$). </p><p>This algorithm is $$$O(N^3)$$$. See my Solution <a href="/contest/1540/submission/120603369" title="Посылка 120603369 от OleschY">120603369</a></p> <div class="spoiler"><b class="spoiler-title">How to calculate P_i</b><div class="spoiler-content" style="display: none;"><p>I wrote myself a small helper DP-program to find the regularities. Let $$$D$$$ be the Distance between $$$A$$$ and $$$B$$$ and $$$d$$$ be the distance from the node $$$N$$$ to $$$B$$$. My educated guess was: $$$P_i=\frac{\sum_{i=0}^{d-1}\binom{D-1}{i} }{2^{D-1}}$$$</p> <div class="spoiler"><b class="spoiler-title">Helper Program</b><div class="spoiler-content" style="display: none;"><p>It checks for a path of some length for each Intervall $$$[A,B]$$$ which is already visited, what the probability to reach one node before the other is. </p> <pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; int solve(int n) { vector&lt;vector&lt;double&gt;&gt; dp(n, vector&lt;double&gt;(n, 0)); for(int i = 0; i &lt; n; ++i) { dp[0][i] = 1; dp[i][n - 1] = 0; } dp[0][n - 1] = -1; for(int w = n; w &gt;= 0; w--) { for(int i = 1; i + w &lt; n - 1; i++) { int l = i; int r = w + i; dp[l][r] = 0.5 * (dp[l - 1][r] + dp[l][r + 1]); } } cout &lt;&lt; n &lt;&lt; &quot;\n\n&quot;; for(int i = 0; i &lt; n; i++) { cout &lt;&lt; dp[i][i]*(1&lt;&lt;(n-2)) &lt;&lt; &quot;\n&quot;; } cout &lt;&lt; &quot;\n\n\n\n&quot;; return 0; } //====================== // Technical stuff //====================== int main() { int ntest = 12; for(int test = 2; test &lt; ntest; ++test) { solve(test); } return 0; } </code></pre></div></div></div></div></div> </div> </div> <div class="reply info"> <a class="comment-808814 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808814 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808814"> <li> <div class="comment"> <table class="comment-table" commentId="808843" commentParentId="808814"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808843" href="?#comment-808843" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808814" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808843" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808843"> <div class="moveup"> <div class="ttypography"><p>Can you explain your solution in a little bit more detail? :')</p></div> </div> </div> <div class="reply info"> <a class="comment-808843 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808843 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808843"> <li> <div class="comment"> <table class="comment-table" commentId="808869" commentParentId="808843"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808869" href="?#comment-808869" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808843" style="font-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="808869" 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="808869" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808869"> <div class="moveup"> <div class="ttypography"><p>Oof, I can give you an image, that shows how the distances from the two DFS are distributed on an example. You can see Nodes $$$A$$$ and $$$B$$$ and the numbers are the distances we write into the nodes. </p><p><img alt=" " src="/predownloaded/d8/2f/d82f98ecd2c1b4bd15b3c40e62476f6ae2741a64.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>If you have specific questions about some steps go ahead and ask. </p></div> </div> </div> <div class="reply info"> <a class="comment-808869 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808869 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808869"> <li> <div class="comment"> <table class="comment-table" commentId="810069" commentParentId="808869"> <tr> <td class="left"> <div style="position: absolute; left: 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/Mrajaryan" style="position: relative;"> <img src='https://userpic.codeforces.org/1377953/avatar/e904b3a3a2eac1ad.jpg'/> </a> <div><a href="/profile/Mrajaryan" title="Newbie Mrajaryan" class="rated-user user-gray">Mrajaryan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 15:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810069" href="?#comment-810069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808869" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810069" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1377953" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810069"> <div class="moveup"> <div class="ttypography"><p>what does the dp states mean in your helper program? I am unable to understand. Can you please explain?</p></div> </div> </div> <div class="reply info"> <a class="comment-810069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810069"> <li> <div class="comment"> <table class="comment-table" commentId="810097" commentParentId="810069"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 18:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810097" href="?#comment-810097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-810069" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810097"> <div class="moveup"> <div class="ttypography"><p>You have Nodes $$$1$$$ through $$$N$$$, neighbouring IDs are connected. The state $$$dp[l][r]$$$ is the probability, that node $$$N$$$ will be reached before node $$$1$$$ with all the nodes $$$l$$$ through $$$r$$$ marked already. Obviously $$$dp[1][x]=0$$$ and $$$dp[x][N]=1$$$ ($$$dp[1][N]$$$ can't happen). The recurrence is $$$dp[l][r]=(dp[l-1][r]+dp[l][r+1])/2$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-810097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808818" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808818" href="?#comment-808818" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808818" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808818"> <div class="moveup"> <div class="ttypography"><p>I can't grasp the editorial of Div 2 D/ Div 1 B. Can somebody provide a more intuitive explanation?</p></div> </div> </div> <div class="reply info"> <a class="comment-808818 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808818 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808818"> <li> <div class="comment"> <table class="comment-table" commentId="808821" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:45">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808821" href="?#comment-808821" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808821" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808821"> <div class="moveup"> <div class="ttypography"><p>same :(</p></div> </div> </div> <div class="reply info"> <a class="comment-808821 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808821 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808821"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808861" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808861" href="?#comment-808861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808861" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808861"> <div class="moveup"> <div class="ttypography"><p>Step 1. use linearity of expectation. The answer is</p> <center>$$$\sum_{a&lt;b} P(b\text{ appears before }a). $$$</center><p>Step 2: Observe that if we start by marking a vertex $$$c$$$ on the path between $$$a$$$ and $$$b$$$, and suppose the next marked vertex on the path is $$$d$$$. Then, the probability that $$$d$$$ is between $$$c$$$ and $$$a$$$ and the probability that $$$d$$$ is between $$$c$$$ and $$$b$$$ are both $$$1/2$$$. This is because there are only two choices for $$$d$$$ and we're choosing uniformly at random. This means that the answer only depends on $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p><p>Step 3: run a dp to calculate the probability that we mark $$$b$$$ before $$$a$$$ given $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808861"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808833" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808833" href="?#comment-808833" style="font-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="808833" 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="808833" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-72" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-72</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808833"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin &gt;&gt; t; while(t--){ int n; cin &gt;&gt; n; long long arr[n]; for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0; for(int i = 0; i &lt; n — 1; i++){ for(int j = arr[i] — 2 — i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } } } cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;; } return 0; }</p><p>/* Accepted code A different approach using arrays (as I don't know what vectors are, haven't read that) I hope this is a optimal approach. Any suggestions related to this are whole-heartedly welcomed. Also, please guide me how could I have optimized the code to a much extent. Thanks in advance! Keep programming! */</p></div> </div> </div> <div class="reply info"> <a class="comment-808833 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808833 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808833"> <li> <div class="comment"> <table class="comment-table" commentId="808844" commentParentId="808833"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808844" href="?#comment-808844" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808833" style="font-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="808844" 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="808844" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-35" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808844"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-808844 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808844 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808844"> <li> <div class="comment"> <table class="comment-table" commentId="808863" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808863" href="?#comment-808863" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808863" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808863"> <div class="moveup"> <div class="ttypography"><p>Not studied yet, I'm still a beginner, but planning to start soon. Thanks for the guidance.</p></div> </div> </div> <div class="reply info"> <a class="comment-808863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808863"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808879" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808879" href="?#comment-808879" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808879" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808879"> <div class="moveup"> <div class="ttypography"><p>once upon a time, I also did problems while not know what vectors are. sad times :'(</p></div> </div> </div> <div class="reply info"> <a class="comment-808879 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808879 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808879"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808926" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808926" href="?#comment-808926" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808926" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808926"> <div class="moveup"> <div class="ttypography"><p>There's no issue in not knowing vectors. Yes they are important I agree but not knowing vectors should not be discouraged. I became expert here without knowing anything about vectors plus he is a beginner so he shouldn't be discouraged like this.</p></div> </div> </div> <div class="reply info"> <a class="comment-808926 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808926 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808926"> <li> <div class="comment"> <table class="comment-table" commentId="808927" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Tech.Maniac" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Tech.Maniac" title="Expert Tech.Maniac" class="rated-user user-blue">Tech.Maniac</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808927" href="?#comment-808927" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808927" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1242860" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808927"> <div class="moveup"> <div class="ttypography"><p>+1, I agree with you. Same I was expert last year solely using arrays</p></div> </div> </div> <div class="reply info"> <a class="comment-808927 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808927 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808927"> <li> <div class="comment"> <table class="comment-table" commentId="809201" commentParentId="808927"> <tr> <td class="left"> <div style="position: absolute; left: 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/Yash.Amin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Yash.Amin" title="Specialist Yash.Amin" class="rated-user user-cyan">Yash.Amin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809201" href="?#comment-809201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808927" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809201" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-28" data-commentUserId="1226462" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-28</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809201"> <div class="moveup"> <div class="ttypography"><p>Bas kar bsdk kitna jhooth bolega</p></div> </div> </div> <div class="reply info"> <a class="comment-809201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809201"> <li> <div class="comment"> <table class="comment-table" commentId="809215" commentParentId="809201"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809215" href="?#comment-809215" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809215" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809215"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-blue" href="/profile/Yash.Amin" title="Эксперт Yash.Amin">Yash.Amin</a> Could you please refrain from using foul language on educational discussions. Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-809215 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809215 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809215"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808928" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808928" href="?#comment-808928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808928" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808928"> <div class="moveup"> <div class="ttypography"><p>Ah my bad, I did not want to come across as being arrogant, but I was genuinely confused that some people did not know vectors although they are using C++.</p></div> </div> </div> <div class="reply info"> <a class="comment-808928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808928"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808839" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamkiller04" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dreamkiller04" title="Newbie dreamkiller04" class="rated-user user-gray">dreamkiller04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808839" href="?#comment-808839" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2089608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808839"> <div class="moveup"> <div class="ttypography"><p>Please add implementations too.</p></div> </div> </div> <div class="reply info"> <a class="comment-808839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808839"> <li> <div class="comment"> <table class="comment-table" commentId="809106" commentParentId="808839"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809106" href="?#comment-809106" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808839" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809106" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809106"> <div class="moveup"> <div class="ttypography"><p>Simply running two loops and checking every case would give a TLE. So, we might want to minimize the number of operations. For this, we would only consider the cases where the sum of indices is a multiple of an element.</p><p>For this, we would first create two loops, one within the other, first loop iterating i from 0 to (n — 1) with an incrementation of 1. By observation, we can see that the first index for which the sum of indices will be a multiple of arr[i] is (arr[i] — 2 — i).</p><p>So, in the nested loop we will run j = (arr[i] — 2 — i) till (n — 1) with an incrementation of arr[i]. We would ignore the cases where j &lt; 0 or j &gt;= n.</p><p>Finally, we need to check for how many cases this holds (arr[i] * arr[j] = i + j + 2 and j &gt; i).</p><p>Suggestions are welcomed!</p></div> </div> </div> <div class="reply info"> <a class="comment-809106 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809106 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809106"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808842" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808842" href="?#comment-808842" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808842" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-64" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-64</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808842"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){</p><p>ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);</p><p>int t;</p><p>cin &gt;&gt; t;</p><p>while(t--){</p><p>int n;</p> <pre>cin &gt;&gt; n;</pre><p>long long arr[n];</p> <pre>for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0;</pre><p>for(int i = 0; i &lt; n — 1; i++){</p> <pre>for(int j = arr[i] &amp;mdash; 2 &amp;mdash; i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } }</pre><p>}</p><p>cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;;</p><p>}</p> <pre>return 0;</pre><p>}</p><p>/* Accepted code</p><p>A different approach using arrays (as I don't know what vectors are, haven't read that)</p><p>I hope this is a optimal approach.</p><p>Any suggestions related to this are whole-heartedly welcomed.</p><p>Also, please guide me how could I have optimized the code to a much extent.</p><p>Thanks in advance!</p><p>Keep programming! </p><p>*/</p></div> </div> </div> <div class="reply info"> <a class="comment-808842 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808842 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808842"> <li> <div class="comment"> <table class="comment-table" commentId="808851" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808851" href="?#comment-808851" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808851" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808851"> <div class="moveup"> <div class="ttypography"><p>Use spoilers for writing codes, please!</p></div> </div> </div> <div class="reply info"> <a class="comment-808851 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808851 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808851"> <li> <div class="comment"> <table class="comment-table" commentId="808870" commentParentId="808851"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808870" href="?#comment-808870" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808851" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808870" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808870"> <div class="moveup"> <div class="ttypography"><p>Actually, this is my first comment. Don't know much of this stuff as of now, but I'll surely take care of it the very next time.</p></div> </div> </div> <div class="reply info"> <a class="comment-808870 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808870 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808870"> <li> <div class="comment"> <table class="comment-table" commentId="809760" commentParentId="808870"> <tr> <td class="left"> <div style="position: absolute; left: 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/sus" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sus" title="Pupil sus" class="rated-user user-green">sus</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 05:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809760" href="?#comment-809760" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808870" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809760" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1749651" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809760"> <div class="moveup"> <div class="ttypography"><p>what problem is your code for</p></div> </div> </div> <div class="reply info"> <a class="comment-809760 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809760 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809760"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808884" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sevlll777" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sevlll777" title="Grandmaster sevlll777" class="rated-user user-red">sevlll777</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808884" href="?#comment-808884" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808884" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="839333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808884"> <div class="moveup"> <div class="ttypography"><p>NICE CODESTYLE!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-808884 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808884 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808884"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809084" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cj2021" style="position: relative;"> <img src='https://userpic.codeforces.org/1927237/avatar/b64ff59bd9dcf385.jpg'/> </a> <div><a href="/profile/cj2021" title="Newbie cj2021" class="rated-user user-gray">cj2021</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809084" href="?#comment-809084" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809084" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1927237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809084"> <div class="moveup"> <div class="ttypography"><p>What is &amp;mdash?</p><p>Just curious to know as haven't seen it before.</p></div> </div> </div> <div class="reply info"> <a class="comment-809084 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809084 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809084"> <li> <div class="comment"> <table class="comment-table" commentId="809097" commentParentId="809084"> <tr> <td class="left"> <div style="position: absolute; left: 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/klahsiv" style="position: relative;"> <img src='https://userpic.codeforces.org/1590145/avatar/1bf86ae3d48e55b.jpg'/> </a> <div><a href="/profile/klahsiv" title="Expert klahsiv" class="rated-user user-blue">klahsiv</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809097" href="?#comment-809097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809084" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590145" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809097"> <div class="moveup"> <div class="ttypography"><p>it is minus (-).</p></div> </div> </div> <div class="reply info"> <a class="comment-809097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808848" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/willy108" style="position: relative;"> <img src='https://userpic.codeforces.org/1439320/avatar/d7f79ed4e8b32e9a.jpg'/> </a> <div><a href="/profile/willy108" title="Master willy108" class="rated-user user-orange">willy108</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808848" href="?#comment-808848" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808848" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="1439320" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808848"> <div class="moveup"> <div class="ttypography"><p>Div2 B can also be done in O(NsqrtN). We know that for a given pair of indeces i+j &lt; 2n, so any pair that a[i] * a[j] &lt; 2n will have to have one of the two terms be &lt;= sqrt(n) (with some off by one errors of course). So the algorithm is to store an array of pairs [array value, index] and sort that array by the value. If the array value is &lt;= sqrt(2n) we can naively loop over the rest of the array in O(n) time and check (be careful about overcount), and if the value is &gt; sqrt(n), we can ignore it. This works since when a[i] * a[j] &lt; 2n one of a[i] or a[j] has to be &lt;= sqrt(2n) and as a result, every pair will be counted.</p></div> </div> </div> <div class="reply info"> <a class="comment-808848 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808848 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808848"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808860" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bcollet" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bcollet" title="Master bcollet" class="rated-user user-orange">bcollet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808860" href="?#comment-808860" style="font-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="808860" 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="808860" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="858059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808860"> <div class="moveup"> <div class="ttypography"><p>I don't understand in div1 C why it's prefix of b, in the case i=3 we have $$$a_1+a_2+a_3=f_1+f_1+b_1+f_1+b_1+b_2$$$ so $$$f_1=(ap_i-2b_1-b_2)$$$ I believe the general formula is something in the taste of $$$f_1=(ap_i-ibp_{i-1}+bpt_{i-1})/i$$$ where bpt_i=b_1+2b_2+...+ib_i, I think I miss something<br />Edit: corrected</p></div> </div> </div> <div class="reply info"> <a class="comment-808860 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808860 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808860"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808865" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ParsaS" style="position: relative;"> <img src='https://userpic.codeforces.org/1590150/avatar/dc2d8c002d2c5e1e.jpg'/> </a> <div><a href="/profile/ParsaS" title="Candidate Master ParsaS" class="rated-user user-violet">ParsaS</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808865" href="?#comment-808865" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808865" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590150" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808865"> <div class="moveup"> <div class="ttypography"><p>Nice problems. thanks for almost fast editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-808865 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808865 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808865"> <li> <div class="comment"> <table class="comment-table" commentId="808871" commentParentId="808865"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/E404_Not_Found" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/E404_Not_Found" title="Expert E404_Not_Found" class="rated-user user-blue">E404_Not_Found</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808871" href="?#comment-808871" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808865" style="font-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="808871" 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="808871" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1662858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808871"> <div class="moveup"> <div class="ttypography"><p>Yes thanks for fast editorial :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808871 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808871 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808871"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808890" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vikash_8090_b" style="position: relative;"> <img src='https://userpic.codeforces.org/1969032/avatar/a0f23c893ae54e74.jpg'/> </a> <div><a href="/profile/vikash_8090_b" title="Newbie vikash_8090_b" class="rated-user user-gray">vikash_8090_b</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808890" href="?#comment-808890" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808890" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="1969032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808890"> <div class="moveup"> <div class="ttypography"><p>is there anyone who can't even solve one question of today's contest ..</p></div> </div> </div> <div class="reply info"> <a class="comment-808890 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808890 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808890"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808892" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808892" href="?#comment-808892" style="font-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="808892" 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="808892" class="CommentVoteFrame" data-commentRating="-6" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808892"> <div class="moveup"> <div class="ttypography"><p>Deleted :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808892 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808892 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808892"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808918" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prituladima" style="position: relative;"> <img src='https://userpic.codeforces.org/116750/avatar/ca46d0256a294b26.jpg'/> </a> <div><a href="/profile/prituladima" title="Pupil prituladima" class="rated-user user-green">prituladima</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808918" href="?#comment-808918" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808918" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="116750" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808918"> <div class="moveup"> <div class="ttypography"><p>Please explain div2c/div1a problem a little bit more. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808918 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808918 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808918"> <li> <div class="comment"> <table class="comment-table" commentId="808921" commentParentId="808918"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808921" href="?#comment-808921" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808918" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808921" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808921"> <div class="moveup"> <div class="ttypography"><p>Try out this <a href="https://youtube.com/c/MagentaCobra">channel</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808921 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808921 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808921"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808950" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jakab922" style="position: relative;"> <img src='https://userpic.codeforces.org/53532/avatar/f9515e974f3ebcb1.jpg'/> </a> <div><a href="/profile/jakab922" title="Specialist jakab922" class="rated-user user-cyan">jakab922</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808950" href="?#comment-808950" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808950" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="53532" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808950"> <div class="moveup"> <div class="ttypography"><p>I don't really understand the need for a recursive function for the stack emptying probabilities in <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a>. I mean given that you have a stack of size <code>n</code> and and <code>m</code> you can basically have an array of size <code>n + m</code> filled with <code>0</code>s and <code>1</code>s where <code>0</code> at the <code>i</code>th place means that the <code>i</code>th element was taken from the first stack. Any such array which has <code>n</code> <code>0</code>s and <code>m</code> <code>1</code>s correspond to one process and it's easy to see that whoever takes the last spot in the array gets emptied later which gives an easy way to calculate the probabilities. Namely $$$\binom{n + m - 1}{n - 1} / \binom{n + m}{n}$$$ for the first and similar to the other. </p></div> </div> </div> <div class="reply info"> <a class="comment-808950 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808950 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808950"> <li> <div class="comment"> <table class="comment-table" commentId="808959" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cuom1999" style="position: relative;"> <img src='https://userpic.codeforces.org/253776/avatar/934152bc42a0b10c.jpg'/> </a> <div><a href="/profile/cuom1999" title="Grandmaster cuom1999" class="rated-user user-red">cuom1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808959" href="?#comment-808959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="253776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808959"> <div class="moveup"> <div class="ttypography"><p>If $$$m=2$$$ and $$$n=1$$$, your approach gives $$$\frac{1}{3}$$$. The correct answer should be $$$\frac{1}{4}$$$. </p><p>P/S: I'm also curious if there is any combinatoric approach for this,<a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808959"> <li> <div class="comment"> <table class="comment-table" commentId="809004" commentParentId="808959"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809004" href="?#comment-809004" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809004" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809004"> <div class="moveup"> <div class="ttypography"><p>I would guess that there’s no easy closed form. You can evaluate in $$$O(n)$$$ however by counting right up paths from $$$(a,0)$$$ to $$$(x,y)$$$ for all $$$a$$$ and multiplying by $$$2^{-steps}$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-809004 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809004 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809004"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809366" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/geekpradd" style="position: relative;"> <img src='https://userpic.codeforces.org/367430/avatar/427394aa7f5a63a0.jpg'/> </a> <div><a href="/profile/geekpradd" title="Candidate Master geekpradd" class="rated-user user-violet">geekpradd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809366" href="?#comment-809366" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809366" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="367430" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809366"> <div class="moveup"> <div class="ttypography"><p>The problem with this is that all the possibilities are not equilikely, consider $$$m=2, n=1$$$ and let $$$1$$$ denote entries from the stack of size $$$n$$$. Then the probability of obtaining $$$100$$$ is $$$1/2$$$, while obtaining $$$010$$$ and $$$001$$$ has a probability of $$$1/4$$$. Your approach assumes a uniform prior probability (in which case the answer is indeed $$$1/3$$$ whereas here it is $$$1/4$$$ which is the probability of getting $$$001$$$)</p></div> </div> </div> <div class="reply info"> <a class="comment-809366 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809366 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809366"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thunderboltz" style="position: relative;"> <img src='https://userpic.codeforces.org/1170396/avatar/4f017b259605bc5c.jpg'/> </a> <div><a href="/profile/thunderboltz" title="Newbie thunderboltz" class="rated-user user-gray">thunderboltz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808951" href="?#comment-808951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170396" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808951"> <div class="moveup"> <div class="ttypography"><p>Problem Div2C/Div1A, Plz somebody explain 3rd hint. I didn't get why this condition must be true </p><p><code>The sum of the values of edges with positive weight must be ≥ the maximum value in the array.</code></p></div> </div> </div> <div class="reply info"> <a class="comment-808951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808951"> <li> <div class="comment"> <table class="comment-table" commentId="808995" commentParentId="808951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808995" href="?#comment-808995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808995" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808995"> <div class="moveup"> <div class="ttypography"><p>I like to think about C this way: The cheapest node is the root, and the most expensive node, X, is the one with the highest value, D. Therefore no matter how we make our edges, we need at least 1 path from node to X with distance D. So let's build 1 single edge of positive weight from 1 to X with weight D.</p><p>Now from node X, all other nodes are &lt;= D. We can use negative edges to go there. Now the problem just becomes &quot;assign as many negative edges as possible&quot; to the rest of the nodes. </p></div> </div> </div> <div class="reply info"> <a class="comment-808995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808995"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808971" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808971" href="?#comment-808971" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808971" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808971"> <div class="moveup"> <div class="ttypography"><p>In problem <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a> I agree with everything up to:</p> <blockquote><p>Once l is reached, we now note that the probability that the process &quot;gets closer&quot; to b is always equal to the probability of getting closer to a.</p> </blockquote><p>I agree with this quote if it was about each individual set of marked nodes and single step for them. Because for any individual set of marked nodes, those probabilities is just one over the number of options at the moment. But I don't understand why I should forget about everything else what happens with other parts of tree, because after single step which is neither towards <strong>a</strong> neither towards <strong>b</strong>, the number of options (nodes we can mark on next step) may change.</p></div> </div> </div> <div class="reply info"> <a class="comment-808971 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808971 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808971"> <li> <div class="comment"> <table class="comment-table" commentId="809006" commentParentId="808971"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809006" href="?#comment-809006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808971" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809006" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809006"> <div class="moveup"> <div class="ttypography"><p>That is correct, but to see how it stays the same you can think of it inductively. Use strong induction and assume probability is the same no matter what the state of the tree is. Then from $$$(x,y)$$$ you always have an equal probability of ending up in one of the two states you can transition to because $$$p$$$ is always the same. Every scenario you enter one state, there’s another scenario with the same probability that enters the other state. So, the probability of entering one of the two states is the same as the other, thus $$$0.5$$$. Hopefully that makes things more clear.</p></div> </div> </div> <div class="reply info"> <a class="comment-809006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809006"> <li> <div class="comment"> <table class="comment-table" commentId="809113" commentParentId="809006"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809113" href="?#comment-809113" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809006" style="font-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="809113" 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="809113" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809113"> <div class="moveup"> <div class="ttypography"><p>Oh thanks, it's clear now. So, base of induction is when only <strong>l</strong> reached, and we can show that probability to make step towards <strong>a</strong> and <strong>b</strong> is same because for each individual set you can go from <strong>l</strong> to <strong>b</strong> instead of going from <strong>l</strong> into <strong>a</strong>, using exactly same steps in between (those steps which doesn't change distances to <strong>a</strong> and <strong>b</strong>). And similar holds for next steps.</p></div> </div> </div> <div class="reply info"> <a class="comment-809113 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809113 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809113"> <li> <div class="comment"> <table class="comment-table" commentId="821713" commentParentId="809113"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 08:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821713" href="?#comment-821713" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809113" style="font-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="821713" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="821713" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-821713"> <div class="moveup"> <div class="ttypography"><p>Can you explain this?</p><p>Assume $$$X$$$ is initially node we chose. Then define a function $$$g$$$ :</p><p>$$$g[a][b][STATE]$$$ = probability to reach a before b while state of the tree we reach is $$$STATE$$$, and $$$a$$$, $$$b$$$ is length of path.</p><p><img alt=" " src="/predownloaded/c2/32/c232d053fe3fbd1dedc06e56db58a7c139157987.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>follow the image, I can see : $$$g[a][b][STATE_x] = \frac{1}{4} (g[a][b][STATE_d] + g[a][b][STATE_e] + g[a — 1][b][closer_a] + g[a][b — 1][closer_b])$$$</p><p>It can easy see that the probability can change. Or I wrong in some where?</p></div> </div> </div> <div class="reply info"> <a class="comment-821713 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821713 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821713"> <li> <div class="comment"> <table class="comment-table" commentId="821861" commentParentId="821713"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 18:25">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821861" href="?#comment-821861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821713" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="821861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-821861"> <div class="moveup"> <div class="ttypography"><p>I'll hide my long explanation under spoiler</p> <div class="spoiler"><b class="spoiler-title">horrible wall of text</b><div class="spoiler-content" style="display: none;"><p>To put things into words, I want to define some things. First, suppose we marked some $$$s_1, s_2, s_3 ... s_k$$$ vertices in exact this order. Then, let $$$P(s)$$$ to be probability to mark them in this sequence. It can be decomposed into $$$P(s) = p_1 \cdot p_2 \cdot p_3 \cdot ... \cdot p_k$$$ where $$$p_i = 1/o_{i-1}$$$ where $$$o_i$$$ is number of options at step $$$i$$$ — number of opened vertices, except $$$p_0 = 1/n$$$, or $$$o_0 = n$$$.</p><p>Then, let $$$l = LCA(a, b)$$$ where $$$LCA$$$ is lowest common ancestor. Then, let $$$x_v$$$ to be some sort of 'cost'. For each $$$v$$$ on path between $$$a$$$ and $$$l$$$ it will be distance to $$$l$$$, and $$$-1$$$ everywhere else. Similarly, for each $$$v$$$ on path between $$$b$$$ and $$$l$$$ let $$$y_v$$$ to be distance to $$$l$$$ and $$$-1$$$ everywhere else. Let</p> <center>$$$ A(s) = \max\limits_{v\in s}x_v \\ B(s) = \max\limits_{v\in s}y_v $$$</center><p>Then $$$A(s)$$$ is equal to how far we reach $$$a$$$, and $$$B(s)$$$ is equal to how far we reach $$$b$$$. Let say we are in situation $$$(A(s), B(s))$$$ after marking $$$s$$$, and therefore situation is pair of numbers. Situation $$$(-1,-1)$$$ corresponds that no vertex is marked on path from $$$a$$$ to $$$b$$$. Situation $$$(0,0)$$$ corresponds to only $$$l$$$ marked on path from $$$a$$$ to $$$b$$$. And situation $$$(1,0)$$$ corresponds to $$$l$$$ and single vertex towards $$$a$$$ is marked.</p><p>Finally, let say sequence of marks $$$s$$$ reached state $$$(A(s), B(s))$$$ if either $$$A(s) = x_{s_k}$$$ or $$$B(s) = y_{s_k}$$$, in other words, last vertex is on path from $$$a$$$ to $$$b$$$ and it did change situation.</p><p>Now, what we want to prove is following:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha+1,\beta)} P(s) = \sum\limits_{s\;reached\;(\alpha,\beta+1)} P(s)$$$</center><p><strong>For some fixed</strong> $$$s_1$$$, which is root we chosen. And the way we prove it is that $$$s$$$ that is reached $$$(\alpha+1,\beta)$$$ consists of $$$u$$$ that reached $$$(\alpha,\beta)$$$ plus additional steps: $$$w$$$ plus $$$s_k$$$. So $$$s = u..w..s_k$$$ where $$$..$$$ is concatenation. It's easy to see what none of vertices from $$$w$$$ is on path from $$$a$$$ to $$$b$$$. Also, it's easy to see that we could instead of choosing $$$s_k$$$ could choose vertex $$$z$$$ towards $$$b$$$, and it would have same probability. In other words $$$P(s) = P(u..w..z)$$$. And this $$$u..w..z$$$ should reach state $$$(\alpha, \beta+1)$$$. So it should be in right side sum of our equation we want to prove.</p><p>So, for any $$$s$$$ from left sum, we can make $$$s'$$$ from right sum in unique way, and it will have same $$$P(s) = P(s')$$$. Similarly, for any $$$s$$$ from right sum, we can make $$$s'$$$ from left sum in unique way, and it will have same $$$P(s) = P(s')$$$. So this is bijection, and each element from left sum corresponds to element from right sum with same value, so those sums should have same value. Therefore it's equality.</p><p>Initially I wanted to trim $$$s$$$ from $$$(\alpha+1,\beta)$$$ to $$$(\alpha,\beta)$$$ and show similar thing based on following sum:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha,\beta)} P(s)$$$</center><p>Which is probability to reach state $$$(\alpha, \beta)$$$, but luckily it didn't required. I'll use notation $$$P(reach(\alpha, \beta))$$$ for this probability.</p><p>Thing that is not covered though: why this equality can be translated into probability $$$= 1/2$$$? Well, from $$$(\alpha, \beta)$$$ you eventually will reach either $$$(\alpha+1,\beta)$$$ or $$$(\alpha,\beta+1)$$$, so you can see this as example of Law of total probability. $$$P(reach(\alpha, \beta)) = P(reach (\alpha+1, \beta)) + P(reach (\alpha, \beta+1))$$$, because events $$$(\alpha+1,\beta)$$$ and $$$(\alpha,\beta+1)$$$ are disjoint events given $$$(\alpha, \beta)$$$ is reached. And we proved they have equal probability so $$$P(reach(\alpha, \beta)) = 2\cdot P(reach (\alpha+1, \beta))$$$, so $$$P(reach (\alpha+1, \beta)) = 1/2\cdot P(reach(\alpha, \beta))$$$ which we actually use.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-821861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821861"> <li> <div class="comment"> <table class="comment-table" commentId="822027" commentParentId="821861"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/28/2021 13:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822027" href="?#comment-822027" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821861" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="822027" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822027"> <div class="moveup"> <div class="ttypography"><p>Oh, sorry, there is one missing part. We proved $$$P(reached(\alpha+1,\beta))=P(reached(\alpha,\beta+1))$$$ <strong>given</strong> $$$(\alpha,\beta)$$$ is reached, but this is actually what we need. This <strong>given</strong> condition is what I missed. Without <strong>given</strong> we could reach $$$(\alpha+1,\beta)$$$ from reaching $$$(\alpha+1,\beta-1)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-822027 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822027 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822027"> <li> <div class="comment"> <table class="comment-table" commentId="822370" commentParentId="822027"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 13:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822370" href="?#comment-822370" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822027" style="font-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="822370" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="822370" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822370"> <div class="moveup"> <div class="ttypography"><p>Thanks for amz explain. I realize that I had some missunderstand in the way we calc $$$P(reach\ A\ before\ B)$$$</p><p>This's exactly what in my mind one day ago: let $$$s = ...a...b...$$$ where $$$a$$$ and $$$b$$$ is node $$$a$$$ and node $$$b$$$, &quot;$$$...$$$&quot; mean some node between them which we chose them in exactly that order, or in other word, $$$s$$$ is state represent what we chose (exact in this order) I think $$$P(reach\ A\ before\ B)$$$ (or $$$P(A&lt;B)$$$) must be calculate in this way :</p><p>$$$P(A&lt;B) = \sum_{\substack{all\ s\ which\ a&lt;b}} P(s)$$$</p><p>But unfortunately, it's wrong (may be, or I still missunderstanding)</p><p>$$$P(A) = \sum_{\substack{all\ B[i]\ \subseteq\ A}} P(B[i])$$$ if and only if all $$$B[i]$$$ are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-822370 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822370 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822370"> <li> <div class="comment"> <table class="comment-table" commentId="822755" commentParentId="822370"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 22:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822755" href="?#comment-822755" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822370" style="font-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="822755" 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="822755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822755"> <div class="moveup"> <div class="ttypography"><p>$$$P(A &lt; B)$$$ in your terms is exactly what we need (if a = A and b = B).</p><p>I don't understand last formula, everything else looks fine.</p><p>And to find $$$P(A &lt; B)$$$ we use fact above and calculate all possible ways to reach $$$a$$$ earlier than $$$b$$$ we use $$$(\alpha, \beta)$$$ states using my notation: you either get $$$\alpha$$$ equal to dist to $$$a$$$ when $$$\beta$$$ = 0, or $$$\beta$$$ = 1, or 2, or 3...</p> <center>$$$ P(A &lt; B) = \\ =\sum\limits_{i=0}^{dist(b,l)}P(reach(dist(a,l),i)\;given\; reached(dist(a,l)-1,i)) \\ = \sum\limits_{i=0}^{dist(b,l)}P(reached(dist(a,l)-1,i))\cdot \frac{1}{2} $$$</center><p>Or you can rephrase task into other task with two kind of balls. What probability to remove all balls of one kind earlier than other, if you pick one or other kind of ball with probability 1/2.</p></div> </div> </div> <div class="reply info"> <a class="comment-822755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822755"> </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="808983" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/xsc" style="position: relative;"> <img src='https://userpic.codeforces.org/343/avatar/9eaf243b1eb8c3d4.jpg'/> </a> <div><a href="/profile/xsc" title="Specialist xsc" class="rated-user user-cyan">xsc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808983" href="?#comment-808983" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808983" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="343" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808983"> <div class="moveup"> <div class="ttypography"><p>Div2 D, O(N^4) solution <a href="/contest/1541/submission/120623566" title="Посылка 120623566 от xsc">120623566</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808983 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808983 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808983"> <li> <div class="comment"> <table class="comment-table" commentId="809278" commentParentId="808983"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DavidXu_JJ" style="position: relative;"> <img src='https://userpic.codeforces.org/2003708/avatar/623dc8036b4e9d72.jpg'/> </a> <div><a href="/profile/DavidXu_JJ" title="Expert DavidXu_JJ" class="rated-user user-blue">DavidXu_JJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809278" href="?#comment-809278" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808983" style="font-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="809278" 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="809278" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2003708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809278"> <div class="moveup"> <div class="ttypography"><p>Your code really helps me a lot in debugging,thanks.</p><p>By the way,it's weired that I get Wrong6 when I try to optimize to O(N^3*logN) by binary search on tree.</p><p>I have tested my function on other online judge and my function seems to be correct.</p></div> </div> </div> <div class="reply info"> <a class="comment-809278 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809278 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809278"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809018" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ducati" style="position: relative;"> <img src='https://userpic.codeforces.org/699102/avatar/eff3c352646e914e.jpg'/> </a> <div><a href="/profile/ducati" title="Grandmaster ducati" class="rated-user user-red">ducati</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 03:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809018" href="?#comment-809018" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809018" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="699102" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809018"> <div class="moveup"> <div class="ttypography"><p>Although Div.2 D is harder than ever, in my opinion, it's such a useful and excellent problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-809018 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809018 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809018"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809046" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KanishkGoel" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/KanishkGoel" title="Expert KanishkGoel" class="rated-user user-blue">KanishkGoel</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809046" href="?#comment-809046" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809046" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1917239" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809046"> <div class="moveup"> <div class="ttypography"><p>Is it usual for people to post solutions online during the contest like this channel? <a href="https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ">https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809046 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809046 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809046"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809051" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809051" href="?#comment-809051" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809051"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain why this submission <a href="/contest/1541/submission/120562335" title="Посылка 120562335 от Karnania7201">120562335</a> is failing for Div2 B? It would be a great help.</p></div> </div> </div> <div class="reply info"> <a class="comment-809051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809051"> <li> <div class="comment"> <table class="comment-table" commentId="809076" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809076" href="?#comment-809076" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809076" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809076"> <div class="moveup"> <div class="ttypography"><p>Bro you did not included the condition that i and j should be different i.e (i != j) because it is given in question that no are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-809076 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809076 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809076"> <li> <div class="comment"> <table class="comment-table" commentId="809079" commentParentId="809076"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:08">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809079" href="?#comment-809079" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809076" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809079" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809079"> <div class="moveup"> <div class="ttypography"><p>I think its covered as I started j from i+1. I tried that explicitly too but it didn't work. I wrote the same idea in a different way and it worked but this kind of implementation is not working.</p></div> </div> </div> <div class="reply info"> <a class="comment-809079 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809079 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809079"> <li> <div class="comment"> <table class="comment-table" commentId="809082" commentParentId="809079"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809082" href="?#comment-809082" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809079" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809082" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809082"> <div class="moveup"> <div class="ttypography"><p>yeah, you are right, I run your code using vector instead of creating memeset it worked fine, i guess there is some problem in that. <a href="https://codeforces.com/contest/1541/submission/120633207">120633207</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809082 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809082 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809082"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809081" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_NICkk" style="position: relative;"> <img src='https://userpic.codeforces.org/1543175/avatar/6084dd87f2c1cad9.jpg'/> </a> <div><a href="/profile/_NICkk" title="Expert _NICkk" class="rated-user user-blue">_NICkk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809081" href="?#comment-809081" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809081" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1543175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809081"> <div class="moveup"> <div class="ttypography"><p>Only fault in your code is that you didn't used memset correctly </p><p>I just changed your memset with this &quot; memset(ind, 0, sizeof(ind)) &quot; and it worked perfectly fine</p></div> </div> </div> <div class="reply info"> <a class="comment-809081 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809081 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809081"> <li> <div class="comment"> <table class="comment-table" commentId="809091" commentParentId="809081"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:37">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809091" href="?#comment-809091" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809081" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809091" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809091"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot to both of you. I shouldn't have used it without properly knowing about it. </p></div> </div> </div> <div class="reply info"> <a class="comment-809091 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809091 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809091"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809064" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vrintle" style="position: relative;"> <img src='https://userpic.codeforces.org/1991777/avatar/24d9007095afbbb6.jpg'/> </a> <div><a href="/profile/vrintle" title="Master vrintle" class="rated-user user-orange">vrintle</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809064" href="?#comment-809064" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809064" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1991777" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809064"> <div class="moveup"> <div class="ttypography"><p>Instead of $$$a_i \cdot a_j \leq 2n$$$, we could also check $$$a_i \cdot a_j \leq i+n$$$ which is a bit faster ($$$ \sim 62ms$$$).</p></div> </div> </div> <div class="reply info"> <a class="comment-809064 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809064 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809064"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809066" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809066" href="?#comment-809066" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809066" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809066"> <div class="moveup"> <div class="ttypography"><p>can anyone explain B. pleasant pairs more easy words?? </p></div> </div> </div> <div class="reply info"> <a class="comment-809066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809066"> <li> <div class="comment"> <table class="comment-table" commentId="809067" commentParentId="809066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809067" href="?#comment-809067" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809067" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809067"> <div class="moveup"> <div class="ttypography"><p>And also what is ask in 3rd question i cant understand what asked in it</p></div> </div> </div> <div class="reply info"> <a class="comment-809067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809067"> <li> <div class="comment"> <table class="comment-table" commentId="809070" commentParentId="809067"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809070" href="?#comment-809070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809067" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809070"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">https://www.youtube.com/watch?v=xCj_ZR5kENo</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809098" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809098" href="?#comment-809098" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809098" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809098"> <div class="moveup"> <div class="ttypography"><p>For those who are searching for a simple solution for great Graphs problems in O (nlogn). <a href="https://codeforces.com/contest/1541/submission/120600816">https://codeforces.com/contest/1541/submission/120600816</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809098 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809098 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809098"> <li> <div class="comment"> <table class="comment-table" commentId="809119" commentParentId="809098"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fjvzr" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/fjvzr" title="Newbie fjvzr" class="rated-user user-gray">fjvzr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809119" href="?#comment-809119" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809098" style="font-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="809119" 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="809119" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1623986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809119"> <div class="moveup"> <div class="ttypography"><p>Bro can u explain this soln????? i thought of taking all pairs that give negative edges except for the adjacent pairs.... bt getting wrong ans in 3rd 4th test case.....</p><p>while(n&gt;2) { sum-=(n-2)*(llabs(a[j]-a[i])); n--; // n = size i++; // i = 0 j--; // j = n-1 } cout&lt;&lt;sum&lt;&lt;endl;</p><p><a href="https://codeforces.com/contest/1541/submission/120636509">mysoln</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809119 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809119 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809119"> <li> <div class="comment"> <table class="comment-table" commentId="809124" commentParentId="809119"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809124" href="?#comment-809124" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809119" style="font-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="809124" 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="809124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809124"> <div class="moveup"> <div class="ttypography"><p>My solution is simple. First sort the array. </p><p>Then start connecting adjacent values with their differences. This way sum of all edges with positive weight will be same as the sum of adjacent differences in the array.</p><p>After that start making negative edges for every i. So each i will have i negative edges. Where negative weight is same as -(arr[i] — arr[j]).</p><p>Instead of search it for every j I have formula as (prefixsum till i) — arr[i]*i</p></div> </div> </div> <div class="reply info"> <a class="comment-809124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809124"> <li> <div class="comment"> <table class="comment-table" commentId="809132" commentParentId="809124"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809132" href="?#comment-809132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809124" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809132"> <div class="moveup"> <div class="ttypography"><p>can you tell me why are we sorting the array for a particular node call it x we need to add a negative weight from x to 1 , x to 2 x to 3 till x to x-1 keeping in mind the the path sum doesn't become negative so why are we sorting the array</p></div> </div> </div> <div class="reply info"> <a class="comment-809132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809132"> <li> <div class="comment"> <table class="comment-table" commentId="809135" commentParentId="809132"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809135" href="?#comment-809135" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809135" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809135"> <div class="moveup"> <div class="ttypography"><p>We are sorting values only once so as to connect neighboring nodes with minimum values,i.e. difference b/w consecutive values.<br /> From this sum of positive edges will be minimum.</p></div> </div> </div> <div class="reply info"> <a class="comment-809135 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809135 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809135"> <li> <div class="comment"> <table class="comment-table" commentId="809139" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809139" href="?#comment-809139" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809139" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809139"> <div class="moveup"> <div class="ttypography"><p>ohhh thanks I got it</p></div> </div> </div> <div class="reply info"> <a class="comment-809139 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809139 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809139"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809145" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809145" href="?#comment-809145" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809145" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809145"> <div class="moveup"> <div class="ttypography"><p>My solution is working now I only needed to sort the array my code would have been accepted during the contest :(</p></div> </div> </div> <div class="reply info"> <a class="comment-809145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809145"> </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="809116" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ken_KaNeKi_997" style="position: relative;"> <img src='https://userpic.codeforces.org/1737228/avatar/50ceb845253df5d4.jpg'/> </a> <div><a href="/profile/Ken_KaNeKi_997" title="Newbie Ken_KaNeKi_997" class="rated-user user-gray">Ken_KaNeKi_997</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809116" href="?#comment-809116" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809116" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1737228" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809116"> <div class="moveup"> <div class="ttypography"><p>can anyone explain div2 B plz</p></div> </div> </div> <div class="reply info"> <a class="comment-809116 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809116 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809116"> <li> <div class="comment"> <table class="comment-table" commentId="809204" commentParentId="809116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809204" href="?#comment-809204" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809116" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809204" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809204"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/92199#comment-809178">here</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809204 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809204 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809204"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809122" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809122" href="?#comment-809122" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809122" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809122"> <div class="moveup"> <div class="ttypography"><p>Beautiful Problems. Amazing Round!!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-809122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809122"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809156" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dummybawa" style="position: relative;"> <img src='https://userpic.codeforces.org/1704408/avatar/1522f670cd21321.jpg'/> </a> <div><a href="/profile/dummybawa" title="Expert dummybawa" class="rated-user user-blue">dummybawa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809156" href="?#comment-809156" style="font-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="809156" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809156" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1704408" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809156"> <div class="moveup"> <div class="ttypography"><p>UPD: It's wrong. </p></div> </div> </div> <div class="reply info"> <a class="comment-809156 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809156 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809156"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809178" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809178" href="?#comment-809178" style="font-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="809178" 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="809178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809178"> <div class="moveup"> <div class="ttypography"><p>For DIV 2C/1A can anyone explain with this test case N = 6 and D = 0 1 2 3 2 3. What are the edges that we can have with their weights?</p></div> </div> </div> <div class="reply info"> <a class="comment-809178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809178"> <li> <div class="comment"> <table class="comment-table" commentId="809198" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Zemrith" style="position: relative;"> <img src='https://userpic.codeforces.org/1159882/avatar/2a6566e372882267.jpg'/> </a> <div><a href="/profile/Zemrith" title="Expert Zemrith" class="rated-user user-blue">Zemrith</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809198" href="?#comment-809198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-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="809198" 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="809198" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159882" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809198"> <div class="moveup"> <div class="ttypography"><p>Hello! The answer would be -18.</p><p>Diagram: <img alt=" " src="/predownloaded/8c/88/8c88a0230dea9f499896ee59def659611c605976.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Notice that once you sort the distances, the adjacent nodes have no effect on your final answer. But you can add negative edges as long as they are not adjacent, resulting in such a diagram. Hence you can use prefix sums to solve the problem. (if x nodes came before this, for each node, the answer to add is (x-1)*curr value — csum of first (x-1) nodes). </p><p>Hope that made sense!</p></div> </div> </div> <div class="reply info"> <a class="comment-809198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809198"> <li> <div class="comment"> <table class="comment-table" commentId="809218" commentParentId="809198"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:27">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809218" href="?#comment-809218" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809218" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809218"> <div class="moveup"> <div class="ttypography"><p>Thank you <a class="rated-user user-cyan" href="/profile/Zemrith" title="Специалист Zemrith">Zemrith</a> for so much detail explanation and the solution too it helped me a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-809218 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809218 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809218"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809199" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809199" href="?#comment-809199" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809199" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809199"> <div class="moveup"> <div class="ttypography"><p>first sort the array they will from non negative weight edges. 0 -&gt; 1 -&gt; 2 -&gt; 2 -&gt; 3 -&gt; 3 so the non negative weights will be 1 | 1 | 0 | 1 | 0. form here greedily build most negative weights(backward edges) such that there are no negative cycles.</p></div> </div> </div> <div class="reply info"> <a class="comment-809199 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809199 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809199"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809203" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809203" href="?#comment-809203" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809203" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809203"> <div class="moveup"> <div class="ttypography"><p>First you can sort D and get: <code> N = 6, D = [0, 1, 2, 2, 3, 3] </code></p><p>Now calculate the diffs:</p><p><code>diffs = [1, 1, 0, 1, 0]</code></p><p>The edges for this graph could be something like this:</p> <pre><code> 1 1 0 1 0 &lt;- forward edges 1 &lt;-&gt; 2 &lt;-&gt; 3 &lt;-&gt; 4 &lt;-&gt; 5 &lt;-&gt; 6 -1 -1 0 -1 0 &lt;- backward edges </code></pre><p>Now you have to add more negatives edges, and you could do this by choosing some <code>i</code> and <code>j</code>, <code>i &lt; j</code> and add an edges from <code>j</code> to <code>i</code>, and the weight will be sum of the values from <code>diff[i]</code> to <code>diff[j]</code>.</p><p>Another way to think about this is: look at <code>D</code> array, it represents distances between adjacent nodes, all we have to do is add all of the edges with length 2, then all of the edges of length 3, ..., all of the edges of length <code>N - 1</code>.</p><p>So, for our case we would have these edges</p> <pre><code>a b W ------- 1 2 - 1 2 3 - 1 3 4 - 0 &lt;- adjacent forward edges 4 5 - 1 5 6 - 0 2 1 - -1 3 2 - -1 4 3 - 0 &lt;- adjacent backward edges 5 4 - -1 6 5 - 0 3 1 - -2 4 2 - -1 5 3 - -1 &lt;- edges of length 2 6 4 - -1 4 1 - -2 5 2 - -2 &lt;- edges of length 3 6 3 - -1 5 1 - -3 6 2 - -2 &lt;- edges of length 4 6 1 - -3 &lt;- edges of length 5 </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809203 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809203 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809203"> <li> <div class="comment"> <table class="comment-table" commentId="809221" commentParentId="809203"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809221" href="?#comment-809221" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809203" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809221" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809221"> <div class="moveup"> <div class="ttypography"><p>Thank You <a class="rated-user user-green" href="/profile/ilidar" title="Ученик ilidar">ilidar</a> for clearing my doubt and for detailed explaination.</p></div> </div> </div> <div class="reply info"> <a class="comment-809221 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809221 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809221"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809280" href="?#comment-809280" style="font-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="809280" revisionCount="7" revision="7"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">7</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809280" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+18</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809280"> <div class="moveup"> <div class="ttypography"><p>Could someone please provide a more strict intuition or insight of Div2D/Div1B of why &quot;the actual probability p does not matter&quot;? The intuition in the editorial is still alien to me of why those choices of not progess toward to either stacks (and probability 'p' also changes from time to time too) doesn't matter.</p><p>Update: Here is the intuition I came up with (The strict proof can be found in the comment of the author below)</p><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left) in some states of the current tree.</p><p>now, we will try break this $$$dp_{i,j}$$$ down into the sum of $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$</p><p>We will try to illustrate this with trying to split and color, either red or blue, a stick of length $$$1$$$. The length of the sticks representing the 'probability', and the color of the sticks will represent $$$dp_{i-1,j}$$$(red) or $$$dp_{i,j-1}$$$(blue), depending on the color.</p><p>Suppose in the current state, we have probability $$$p$$$ for choosing to pop each stacks, and the rest $$$1-2p$$$ of doing nothing. The picture will look like this:</p><p><a href="https://ibb.co/q9HjQTm"><img alt="Tree-Array-Rep" border="0" src="/predownloaded/13/57/135732d2b0967af0f76c1dba28df72086f234c7d.png" style="max-width: 100.0%;max-height: 100.0%;" /></a></p><p>We will split the stick equally(*) into several sticks of length $$$p$$$, and then color two of them red and blue. (* We can split it evenly because in the original problem, $$$p$$$ is in the form $$$\frac{1}{number\ of\ candidate\ unmark\ nodes}$$$ ) Now, the remaining sticks represent the state of $$$dp_{i,j}$$$ again (in some other state of the entire tree, so might be in some different $$$p$$$). That means we will split those sticks similary.</p><p>The key observations is:</p><p>1) We know that, in the original problem, if we keep picking nodes that aren't progressing toward the target nodes, we will run out of nodes eventually and finally choose the two nodes. That means, all the sticks will eventually colored into 'red' and 'blue'.</p><p>2) When we split a stick into several smaller equal length sticks, we will color two of them into red and blue. <strong>Those two sticks always have the same length</strong>. That means, the total length of blue sticks and the total length of red sticks will be equal in the end.</p><p>Analogically, that means, eventually, $$$dp_{i,j}$$$ will split into $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$ evenly, no matter $$$p$$$ might be or the state of tree of $$$dp_{i,j}$$$ might be. Therefore, $$$dp_{i,j} = \frac{1}{2} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-809280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809280"> <li> <div class="comment"> <table class="comment-table" commentId="809284" commentParentId="809280"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809284" href="?#comment-809284" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809280" style="font-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="809284" 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="809284" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809284"> <div class="moveup"> <div class="ttypography"><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left), with having arbitary probability $$$0 &lt; p \leq 0.5$$$ of chosing to pick the top of each stack (and $$$1-2p$$$ for doing nothing). Then</p><p>$$$dp_{i,j}=\int_{0}^{0.5} x \cdot (dp_{i-1,j}+dp_{i,j-1}) + (1-2x) \cdot dp_{i,j} \,dx$$$</p><p>Solving the equation, we get $$$dp_{i,j}=\frac{1}{6} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$ What is the mistake in this logic?</p></div> </div> </div> <div class="reply info"> <a class="comment-809284 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809284 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809284"> <li> <div class="comment"> <table class="comment-table" commentId="809399" commentParentId="809284"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809399" href="?#comment-809399" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809284" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809399" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809399"> <div class="moveup"> <div class="ttypography"><p>The biggest issue with this logic is that it's assuming $$$p$$$ is arbitrary chosen from a certain state. While $$$p$$$ can be anything in the world, it is always an exact number from a certain state, hence why an integral is wrong. </p><p>As a different type of intuition, you can think, &quot;is it more likely to reach $$$(i-1, j)$$$ than state $$$(i, j-1)$$$&quot;? and vice versa. For me at least, I don't see how it's possible for either of those questions to be true, so they should be equal.</p><p>If you're looking for a more rigorously correct $$$dp$$$, it would look something like this.</p> <div class="spoiler"><b class="spoiler-title">Proof</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp_{i, j, S}$$$ denote the probability of reaching some node $$$i$$$ distance away before some node $$$j$$$ distance away where $$$S$$$ is a representation of the entire state of of the process (not necessarily an integer). I think you already understood why we can assume the $$$lca$$$ is already reached. We aim to show that $$$S$$$ does not matter in our calculation. Assume inductively that $$$S$$$ does not matter. So, we can assume that states $$$(i-1, j)$$$ and states $$$(i, j-1)$$$ are irrelevant to $$$S$$$. Hence, the part we need to care about is $$$(1-2p) dp_{i, j, S \rightarrow S_a}$$$. A way of thinking about this part of the transition is moving through the collection of $$$S$$$ with the state $$$(i, j)$$$. Obviously, the $$$dp$$$ is a $$$DAG$$$ because no state $$$S$$$ can reach another. Each bounce takes a certain probability $$$p$$$ which is just multiplied in the current path. So, for each state $$$S$$$ with state $$$(i, j)$$$, we have a certain probability to reach it by simply calculating $$$dp$$$ along a DAG as is traditional. Then, from those states of $$$(i, j)$$$ you transition to $$$(i, j-1)$$$ with an equal probability $$$(i-1, j)$$$. So, they have to be equal. Finally, this argument holds for any initial state $$$S$$$ that you reach, so we can conclude that, from any state $$$S$$$ with a state of $$$(i, j)$$$, the probability of transitions to $$$(i-1, j)$$$ and $$$(i, j-1)$$$ are always exactly $$$0.5$$$.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-809399 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809399 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809399"> <li> <div class="comment"> <table class="comment-table" commentId="809701" commentParentId="809399"> <tr> <td class="left"> <div style="position: absolute; left: 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/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809701" href="?#comment-809701" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809399" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809701" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809701"> <div class="moveup"> <div class="ttypography"><p>I see, thank you so much!</p></div> </div> </div> <div class="reply info"> <a class="comment-809701 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809701 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809701"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809298" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/satyam_singh93" style="position: relative;"> <img src='https://userpic.codeforces.org/1763011/avatar/9d9fa405de19ab0e.jpg'/> </a> <div><a href="/profile/satyam_singh93" title="Newbie satyam_singh93" class="rated-user user-gray">satyam_singh93</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809298" href="?#comment-809298" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809298" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1763011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809298"> <div class="moveup"> <div class="ttypography"><p>I am getting wrong ans . could someone tell me where the code make differene ( [yestrday competiton problem .</p><p>`](<a href="https://codeforces.com/contest/1541/problem/B)">https://codeforces.com/contest/1541/problem/B)</a>.</p> <pre><code>int main( ) { clock_t begin = clock(); file_i_o(); // Write your code here.... int t; cin&gt;&gt;t; while(t-- ){ int n; cin&gt;&gt;n; vector&lt;pair&lt;int,int&gt;&gt;v; v.push_back({0,0}); loop(i,0,n) { int x; cin&gt;&gt;x; v.pb({x,i+1}); } sort(v.begin()+1,v.end()); int count =0; for(int i=1 ; i&lt;=n;i++) { for(ll j=i+1;j&lt;=n;j++) { ll left = v[i].first * v[j].first; ll right = v[i].second + v[j].second; if(left == right) count++; if(left &gt; 2*n ) break; } } cout&lt;&lt;count&lt;&lt;endl; } </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809298 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809298 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809298"> <li> <div class="comment"> <table class="comment-table" commentId="809305" commentParentId="809298"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809305" href="?#comment-809305" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809298" style="font-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="809305" 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="809305" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809305"> <div class="moveup"> <div class="ttypography"><p>v[i].first * v[j].first can create overflow. So, you need to convert them to long long by using</p><p>ll left = 1LL * v[i].first * v[j].first;</p><p>instead and it would pass.</p><p>(Simply save the value in long long won't help. You need to convert them to long long before doing multiplication. 1LL* is one way)</p></div> </div> </div> <div class="reply info"> <a class="comment-809305 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809305 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809305"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809309" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809309" href="?#comment-809309" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809309" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809309"> <div class="moveup"> <div class="ttypography"><p>Hi, in problem Div1.B/Div2.D; I can't wrap my head around $$$F[x][y]=F[x−1][y]/2+F[x][y−1]/2$$$. Why is it not $$$F[x][y]=F[x−1][y+1]/2+F[x+1][y−1]/2$$$, can someone please explain to me why is my transition wrong and/or why is the aforementioned transition correct? </p></div> </div> </div> <div class="reply info"> <a class="comment-809309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809309"> <li> <div class="comment"> <table class="comment-table" commentId="809311" commentParentId="809309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809311" href="?#comment-809311" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809311" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809311"> <div class="moveup"> <div class="ttypography"><p>x and y is the distance left for each side right? So, if you take one out, it won't make sense to add that one to the other side since the distance should be either x-1 and y or x and y-1.</p></div> </div> </div> <div class="reply info"> <a class="comment-809311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809311"> <li> <div class="comment"> <table class="comment-table" commentId="809339" commentParentId="809311"> <tr> <td class="left"> <div style="position: absolute; left: 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/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809339" href="?#comment-809339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809339" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809339"> <div class="moveup"> <div class="ttypography"><p>Thank you so much I understand. I had a minor misunderstanding of the parameters to the dp state.</p></div> </div> </div> <div class="reply info"> <a class="comment-809339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809339"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809371" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:13">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809371" href="?#comment-809371" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809371" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809371"> <div class="moveup"> <div class="ttypography"><p>PLease explain why 2 same codes are not giving the same ans</p><p>code forces round 728 div2<br />Problem B :<a href="https://codeforces.com/contest/1541/problem/B">https://codeforces.com/contest/1541/problem/B</a></p><p>AC Submission : <a href="https://ide.codingblocks.com/s/579769">https://ide.codingblocks.com/s/579769</a></p><p>Wrong output Submission :<a href="https://ide.codingblocks.com/s/579771">https://ide.codingblocks.com/s/579771</a></p><p>Difference is using of macro (node) instead of pair&lt;int,int&gt; </p><p>Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-809371 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809371 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809371"> <li> <div class="comment"> <table class="comment-table" commentId="809379" commentParentId="809371"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809379" href="?#comment-809379" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809371" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809379" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809379"> <div class="moveup"> <div class="ttypography"><p>If i am using #define node pair&lt;int,int&gt; it is getting accepted but when i am using typedef pair&lt;int,int&gt; node; it is giving wrong answer</p><p>Why this is happening ?? Is it a bug??</p></div> </div> </div> <div class="reply info"> <a class="comment-809379 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809379 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809379"> <li> <div class="comment"> <table class="comment-table" commentId="809407" commentParentId="809379"> <tr> <td class="left"> <div style="position: absolute; left: 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/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 19:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809407" href="?#comment-809407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809379" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809407" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809407"> <div class="moveup"> <div class="ttypography"><p>Not really sure why this is happening.</p><p>However, I think the problem is the position of #define int long long. So, for #define pair&lt;int,int&gt; node it seems that compiler change node -&gt; pair&lt;int,int&gt; -&gt; pair&lt;long long, long long&gt;. However, when you do typedef, it still keeps in pair&lt;int, int&gt; which creates an overflow problem later on. </p><p>I did try moving #define int long long up above typedef and the code pass. So, my best guess is #define int long long only replace int after that position with long long. Thus, node is still pair&lt;int, int&gt; in the typedef solution, while node is changed to pair&lt;long long, long long&gt; in the second solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-809407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809407"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809627" href="?#comment-809627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809627"> <div class="moveup"> <div class="ttypography"><p>May I ask why in the Div1D solution ci=i-bi, I think it should be ci=bi ...</p></div> </div> </div> <div class="reply info"> <a class="comment-809627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809627"> <li> <div class="comment"> <table class="comment-table" commentId="809631" commentParentId="809627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809631" href="?#comment-809631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809631" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809631"> <div class="moveup"> <div class="ttypography"><p>Check the definition of bi again dude. bi here means <strong>number of elements greater than pi</strong>. So to get ci, which is <strong>number of elements smaller than pi</strong>, you need i-bi.</p></div> </div> </div> <div class="reply info"> <a class="comment-809631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809631"> <li> <div class="comment"> <table class="comment-table" commentId="809636" commentParentId="809631"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809636" href="?#comment-809636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809636"> <div class="moveup"> <div class="ttypography"><p>I read it again. If I read it correctly, bi stands for j&lt;i,pj&gt;pi, and ci stands for j&gt;i,pj&lt;pi. For example, p={1,3,5,4,6,2}, I think b4=1,c4=1, please point out my problem</p></div> </div> </div> <div class="reply info"> <a class="comment-809636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809636"> <li> <div class="comment"> <table class="comment-table" commentId="809638" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809638" href="?#comment-809638" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809638" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809638"> <div class="moveup"> <div class="ttypography"><p>oh, the array index starts from 1</p></div> </div> </div> <div class="reply info"> <a class="comment-809638 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809638 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809638"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809639" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809639" href="?#comment-809639" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809639" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809639"> <div class="moveup"> <div class="ttypography"><p>You are right.</p><p>I guess it might just be typo and ci stands for j&lt;i, pj&lt;pi. At least with this definition of ci the algorithm seems correct :)</p></div> </div> </div> <div class="reply info"> <a class="comment-809639 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809639 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809639"> <li> <div class="comment"> <table class="comment-table" commentId="809641" commentParentId="809639"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809641" href="?#comment-809641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809639" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809641"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-809641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809641"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809705" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/darthrevenge" style="position: relative;"> <img src='https://userpic.codeforces.org/1567000/avatar/ee31d2a91a9575b9.jpg'/> </a> <div><a href="/profile/darthrevenge" title="Candidate Master darthrevenge" class="rated-user user-violet">darthrevenge</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809705" href="?#comment-809705" style="font-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="809705" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809705" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1567000" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809705"> <div class="moveup"> <div class="ttypography"><p>Here's my solution of B div 1 / D div 2 without LCA, using single DFS per node. <a href="/contest/1540/submission/120700765" title="Посылка 120700765 от darthrevenge">120700765</a> It is similar to what <a class="rated-user user-violet" href="/profile/OleschY" title="Кандидат в мастера OleschY">OleschY</a> suggested above. I've tried to describe it in the <a href="https://codeforces.com/blog/entry/92284">blog</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-809705 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809705 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809705"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809951" href="?#comment-809951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809951"> <div class="moveup"> <div class="ttypography"><p>Can someone explain how you can find the LCA for each pair so quick? Iterating through every root is and then considering every pair is already N^3</p></div> </div> </div> <div class="reply info"> <a class="comment-809951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809951"> <li> <div class="comment"> <table class="comment-table" commentId="809965" commentParentId="809951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PurpleCrayon" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809965" href="?#comment-809965" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809965" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="1604355" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809965"> <div class="moveup"> <div class="ttypography"><p>There are a couple ways you could do it:</p> <ol> <li>Just use standard binary lifting (initialize once for each root). This runs in $$$\mathcal{O}(n^3 \log{}n)$$$, and should pass under the given constraints. You could also just use $$$\mathcal{O}(1)$$$ lca using an rmq over an euler tour.</li> <li>You could use a version of dp, where $$$dp[a][b] = lca(a, b)$$$. If the depth of $$$a$$$ is greater than the depth of $$$b$$$, $$$dp[a][b] = dp[parent[a]][b]$$$, otherwise $$$dp[a][b] = dp[a][parent[b]]$$$. The base cases are $$$dp[a][a] = a$$$ for all $$$a$$$. This runs in $$$\mathcal{O}(n^3)$$$.</li> <li>You could extend this idea and do the main solution's dp directly on the tree (without ever worrying about lca's). The recurrence is equivalent to the main solution ($$$dp[a][b] = \frac{dp[parent[a]][b]+dp[a][parent[b]]}{2}$$$ with the base cases being one node is an ancestor of the other.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-809965 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809965 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809965"> <li> <div class="comment"> <table class="comment-table" commentId="809967" commentParentId="809965"> <tr> <td class="left"> <div style="position: absolute; left: 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/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809967" href="?#comment-809967" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809965" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809967" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809967"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the detailed answer!</p></div> </div> </div> <div class="reply info"> <a class="comment-809967 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809967 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809967"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="810320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Anurag_20" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Anurag_20" title="Specialist Anurag_20" class="rated-user user-cyan">Anurag_20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/30/2021 19:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810320" href="?#comment-810320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810320" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1600346" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810320"> <div class="moveup"> <div class="ttypography"><p>O(n2) is also working for div2 C Great Graphs. <a href="https://codeforces.com/contest/1540/submission/120964787">https://codeforces.com/contest/1540/submission/120964787</a></p></div> </div> </div> <div class="reply info"> <a class="comment-810320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810320"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="813828" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/T404" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/T404" title="Master T404" class="rated-user user-orange">T404</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/09/2021 19:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-813828" href="?#comment-813828" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="813828" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="523287" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-813828"> <div class="moveup"> <div class="ttypography"><p>Div1D can be done in $$$O(n \sqrt{n})$$$. We can use square root decomposition to replace all BITs in tutorial. Since a value in a non-updated position changes by at most one and all values change in the same direction, the full recomputation is only needed in the updated position and we can perform an incremental change in $$$O(1)$$$ for values in each non-updated positions.</p><p><a href="https://codeforces.com/contest/1540/submission/121831547">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-813828 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-813828 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-813828"> <li> <div class="comment"> <table class="comment-table" commentId="834051" commentParentId="813828"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KeyID" style="position: relative;"> <img src='https://userpic.codeforces.org/226684/avatar/10e3671716bf6859.jpg'/> </a> <div><a href="/profile/KeyID" title="Grandmaster KeyID" class="rated-user user-red">KeyID</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/29/2021 12:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-834051" href="?#comment-834051" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-813828" style="font-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="834051" 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="834051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="226684" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-834051"> <div class="moveup"> <div class="ttypography"><p>Realy impressive solution. I'm surprised no stars were given to you until me. Maybe many people didn't get your idea since the solution is actually much more complicated than your brief comment(at least in my opinion). I also wrote a piece of code which used your method but simplified a small part of steps. <a href="https://codeforces.com/contest/1540/submission/127317031">Here</a> it is.</p></div> </div> </div> <div class="reply info"> <a class="comment-834051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-834051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-834051"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="837924" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Harolinch" style="position: relative;"> <img src='https://userpic.codeforces.org/427341/avatar/cf8608aeb55edc95.jpg'/> </a> <div><a href="/profile/Harolinch" title="Pupil Harolinch" class="rated-user user-green">Harolinch</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837924" href="?#comment-837924" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837924" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="427341" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837924"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a> in problem Tree array you said that Fixing a given root r, the expected value of the entire process is obviously the sum of the expected values for a fixed root divided by n.</p><p>why we divide by n at the end ? </p></div> </div> </div> <div class="reply info"> <a class="comment-837924 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837924 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837924"> <li> <div class="comment"> <table class="comment-table" commentId="837928" commentParentId="837924"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837928" href="?#comment-837928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-837924" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837928" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837928"> <div class="moveup"> <div class="ttypography"><p>The calculation is independent based on whichever node that you choose first (it becomes the “root”). Initially you choose one of $$$n$$$ nodes with equal probability so you divide by $$$n$$$ at the end after you’ve summed up the independent expected value after choosing the node $$$i$$$ initially.</p></div> </div> </div> <div class="reply info"> <a class="comment-837928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837928"> </ul> </div> </li> </ul> </div> <br/> <div id="editBox-100805" 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 firstPreview100805 = true; var lastPreviewContent100805 = ''; 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=100805] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=100805] 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-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, 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:33:28</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:'81289372dffb0c4e',t:'MTY5NjcwNzIwOC45MzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1541C
1541
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$$$ пастбищ, соединенных с помощью односторонних дорог. У каждой дороги есть вес, означающий время, которое необходимо потратить, чтобы пройти по ней. Дороги могут иметь отрицательный вес, иными словами, коровы по ним движутся так быстро, что способны перемещаться назад во времени! Однако, Фермер Джон гарантирует, что коровы никак не смогут попасть во временную петлю в том смысле, что не смогут, двигаясь по дорогам, уйти бесконечно далеко в прошлое. Кроме того, каждая пара пастбищ соединена не более чем одной дорогой в каждом направлении.</p><p>К сожалению, Фермер Джон потерял карту фермы. Все, что он знает — это массив $$$d$$$, где $$$d_i$$$ — это минимальное время, за которое коровы могут добраться до $$$i$$$-го пастбища из $$$1$$$-го, двигаясь по дорогам. Стоимость его фермы — это сумма весов всех дорог, и Фермер Джон хочет узнать <span class="tex-font-style-bf">минимально</span> возможную стоимость фермы, которая не противоречит тому, что он помнит.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора задано одно целое число $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — количество пастбищ.</p><p>Во второй строке каждого набора заданы $$$n$$$ целых чисел через пробел $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — массив $$$d$$$. Гарантируется, что $$$d_1 = 0$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора, выведите минимально возможную стоимость фермы, которая не противоречит воспоминаниям Фермера Джона.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 0 2 3 2 0 1000000000 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -3 0 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе вы можете добавить дороги </p><ul> <li> от пастбища $$$1$$$ к пастбищу $$$2$$$ с весом $$$2$$$, </li><li> от пастбища $$$2$$$ к пастбищу $$$3$$$ с весом $$$1$$$, </li><li> от пастбища $$$3$$$ к пастбищу $$$1$$$ с весом $$$-3$$$, </li><li> от пастбища $$$3$$$ к пастбищу $$$2$$$ с весом $$$-1$$$, </li><li> от пастбища $$$2$$$ к пастбищу $$$1$$$ с весом $$$-2$$$. </li></ul> Суммарная стоимость равна $$$2 + 1 + -3 + -1 + -2 = -3$$$.<p>Во втором набор вы можете добавить дорогу от пастбища $$$1$$$ к пастбищу $$$2$$$ с весом $$$1000000000$$$ и дорогу от пастбища $$$2$$$ к пастбищу $$$1$$$ со стоимостью $$$-1000000000$$$. Суммарная стоимость равна $$$1000000000 + -1000000000 = 0$$$.</p><p>В третьем наборе, вы не можете добавить ни одной дороги. Суммарная стоимость равна $$$0$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="7c01358afaff33a8f6fba11a386392ed"/> <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="3a2e30eec6604291efb1f3ef212d19e2d7715bd7"/> <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='7c01358afaff33a8f6fba11a386392ed'>&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%2F1541%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='7c01358afaff33a8f6fba11a386392ed'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1541">Codeforces Round 728 (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='7c01358afaff33a8f6fba11a386392ed'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1541/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='7c01358afaff33a8f6fba11a386392ed'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1027094"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7c01358afaff33a8f6fba11a386392ed'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1027094"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92093" title="Codeforces Round #728" target="_blank">Codeforces Round #728 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13929" resourceName="Codeforces Round #728" resourceManual="true" src="//codeforces.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/92199" title="Tutorial" target="_blank">Tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13941" 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/1541">Задачи</a></li> <li><a href="/contest/1541/submit">Отослать</a></li> <li><a href="/contest/1541/my">Мои посылки</a></li> <li><a href="/contest/1541/status">Статус</a></li> <li><a href="/contest/1541/hacks">Взломы</a></li> <li><a href="/contest/1541/room/1">Комната</a></li> <li><a href="/contest/1541/standings">Положение</a></li> <li><a href="/contest/1541/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_ff368b24ad144e94092a50e7a80b4f6a1f84d793"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ пастбищ, соединенных с помощью односторонних дорог. У каждой дороги есть вес, означающий время, которое необходимо потратить, чтобы пройти по ней. Дороги могут иметь отрицательный вес, иными словами, коровы по ним движутся так быстро, что способны перемещаться назад во времени! Однако, Фермер Джон гарантирует, что коровы никак не смогут попасть во временную петлю в том смысле, что не смогут, двигаясь по дорогам, уйти бесконечно далеко в прошлое. Кроме того, каждая пара пастбищ соединена не более чем одной дорогой в каждом направлении.</p><p>К сожалению, Фермер Джон потерял карту фермы. Все, что он знает — это массив $$$d$$$, где $$$d_i$$$ — это минимальное время, за которое коровы могут добраться до $$$i$$$-го пастбища из $$$1$$$-го, двигаясь по дорогам. Стоимость его фермы — это сумма весов всех дорог, и Фермер Джон хочет узнать <span class="tex-font-style-bf">минимально</span> возможную стоимость фермы, которая не противоречит тому, что он помнит.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора задано одно целое число $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — количество пастбищ.</p><p>Во второй строке каждого набора заданы $$$n$$$ целых чисел через пробел $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — массив $$$d$$$. Гарантируется, что $$$d_1 = 0$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора, выведите минимально возможную стоимость фермы, которая не противоречит воспоминаниям Фермера Джона.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 0 2 3 2 0 1000000000 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -3 0 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе вы можете добавить дороги </p><ul> <li> от пастбища $$$1$$$ к пастбищу $$$2$$$ с весом $$$2$$$, </li><li> от пастбища $$$2$$$ к пастбищу $$$3$$$ с весом $$$1$$$, </li><li> от пастбища $$$3$$$ к пастбищу $$$1$$$ с весом $$$-3$$$, </li><li> от пастбища $$$3$$$ к пастбищу $$$2$$$ с весом $$$-1$$$, </li><li> от пастбища $$$2$$$ к пастбищу $$$1$$$ с весом $$$-2$$$. </li></ul> Суммарная стоимость равна $$$2 + 1 + -3 + -1 + -2 = -3$$$.<p>Во втором набор вы можете добавить дорогу от пастбища $$$1$$$ к пастбищу $$$2$$$ с весом $$$1000000000$$$ и дорогу от пастбища $$$2$$$ к пастбищу $$$1$$$ со стоимостью $$$-1000000000$$$. Суммарная стоимость равна $$$1000000000 + -1000000000 = 0$$$.</p><p>В третьем наборе, вы не можете добавить ни одной дороги. Суммарная стоимость равна $$$0$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c7039e019dab',t:'MTY5NjY2NzM3Ny4yNzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438 \u043d\u0430 \u0433\u0440\u0430\u0444\u0430\u0445", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1400"]
https://codeforces.com/blog/entry/92199
<!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="ea33d124a1ff874ace73f937748d303e"/> <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="Codeforces Round #728 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #728 Editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='ea33d124a1ff874ace73f937748d303e'>&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%2F92199">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='ea33d124a1ff874ace73f937748d303e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:31:32</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:31:32</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='ea33d124a1ff874ace73f937748d303e'/> <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/PurpleCrayon">PurpleCrayon</a></li> <li class="current selectedLava"><a href="/blog/PurpleCrayon">Blog</a></li> <li><a href="/teams/with/PurpleCrayon">Teams</a></li> <li><a href="/submissions/PurpleCrayon">Submissions</a></li> <li><a href="/groups/with/PurpleCrayon">Groups</a></li> <li><a href="/contests/with/PurpleCrayon">Contests</a></li> <li><a href="/contests/writer/PurpleCrayon">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/PurpleCrayon" style="text-decoration:none;color:black !important;">PurpleCrayon's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="92809"> <div class="title"> <a href="/blog/entry/92199"> <p>Codeforces Round #728 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a>, <a href="/topic/92809/en10">history</a>, <span class="format-humantime" title="Jun/25/2021 20:44">2 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><a href="/contest/1541/problem/A" title="Codeforces Round 728 (Div. 2)">1541A - Pretty Permutations</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The parity (whether $$$n$$$ is odd or even) matters.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Swapping two adjacent cats keeps both of them close to their original location and changes both of their locations.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>If $$$n$$$ is even, the optimal distance is $$$n$$$, and if $$$n$$$ is odd the optimal distance is $$$n+1$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541A">Tutorial is loading...</div></div></div><p><a href="/contest/1541/problem/B" title="Codeforces Round 728 (Div. 2)">1541B - Pleasant Pairs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>$$$i+j \leq 2 \cdot n$$$</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The number of pairs $$$(a, b)$$$ such that $$$a \cdot b \leq x$$$ is $$$O(x log x)$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/A" title="Codeforces Round 728 (Div. 1)">1540A - Great Graphs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What's the minimum value that an edge from $$$a$$$ to $$$b$$$ can be?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use edges with negative value whenever you can.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The sum of the values of edges with positive weight must be $$$\geq$$$ the maximum value in the array.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540A">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Tree Array</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Fix the initial node chosen and root the tree there, what is the contribution of each pair of nodes?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Nothing matters besides the path from node $$$a$$$ to node $$$b$$$, and the initially chosen node $$$r$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>You are given two stacks of size $$$a_1$$$ and $$$a_2$$$. In a single step, you randomly choose a stack to remove a single item from. What is the probability that $$$a_1$$$ becomes $$$0$$$ before $$$a_2$$$? Can you extend this argument for an arbitrary probability $$$p$$$ to remove from one of the two stacks, and a probability of $$$1-2p$$$ to do nothing?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/C2" title="Codeforces Round 728 (Div. 1)">1540C2 - Converging Array (Hard Version)</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What are the invariants? The monovariants?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What is the prefix sum array of the converged array? What is the difference array of the converged array?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you conducted the process on a prefix of size $$$1$$$, then of size $$$2$$$, and on and on?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How many values $$$x$$$ are actually interesting?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540C2">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Inverse Inversions</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The answer is always unique.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Try to figure out what the location of the $$$i$$$-th element would be if you only looked at the first $$$i$$$ elements, then the first $$$i+1$$$, etc. to find an $$$O(nq)$$$ solution.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use sqrt decomposition to optimize it.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540D">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/E" title="Codeforces Round 728 (Div. 1)">1540E - Tasty Dishes</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How much does each chef's initial dish contribute at time $$$k$$$?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you really, really wanted to use matrix exponentiation?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How can you multiply some vectors by a matrix in $$$O(N)$$$ time? (go back to linear algebra class)</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Decompose into linear combinations of eigenvectors.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540E">Tutorial is loading...</div></div></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/1540" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 1)</a> </span> </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/1541" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-191295-92809").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "191295", blogEntryId: "92199", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-92809"><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'>+96</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-92809"><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/PurpleCrayon"><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/PurpleCrayon"> PurpleCrayon </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="Jun/25/2021 20:44">2 years ago</span> </li> <li> <a href="/blog/entry/92199#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/92199#comments"> 170 </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="100805"> <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 (136)</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="808750" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808750" href="?#comment-808750" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808750" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-66" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-66</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808750"> <div class="moveup"> <div class="ttypography"><p>PURPLECRAYON ORZ</p></div> </div> </div> <div class="reply info"> <a class="comment-808750 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808750 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808750"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808751" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hbarp" style="position: relative;"> <img src='https://userpic.codeforces.org/1387715/avatar/c727a810db6ffb66.jpg'/> </a> <div><a href="/profile/hbarp" title="Candidate Master hbarp" class="rated-user user-violet">hbarp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808751" href="?#comment-808751" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808751" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="1387715" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-83</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808751"> <div class="moveup"> <div class="ttypography"><p>Damn, so orz round. <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Мастер PurpleCrayon">PurpleCrayon</a> orz</p></div> </div> </div> <div class="reply info"> <a class="comment-808751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808751"> <li> <div class="comment"> <table class="comment-table" commentId="808805" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/naman1601" style="position: relative;"> <img src='https://userpic.codeforces.org/1703219/avatar/d63fc523dc05fda8.jpg'/> </a> <div><a href="/profile/naman1601" title="Master naman1601" class="rated-user user-orange">naman1601</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808805" href="?#comment-808805" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808805" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-51" data-commentUserId="1703219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-51</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808805"> <div class="moveup"> <div class="ttypography"><p>yeah, amazing problemset, not speedforces at all :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808805 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808805 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808805"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808817" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LOVELY_BOY_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/LOVELY_BOY_" title="Newbie LOVELY_BOY_" class="rated-user user-gray">LOVELY_BOY_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808817" href="?#comment-808817" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-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="808817" 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="808817" class="CommentVoteFrame" data-commentRating="35" data-commentUserId="2089809" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808817"> <div class="moveup"> <div class="ttypography"><p>LOL <a class="rated-user user-blue" href="/profile/hbarp" title="Эксперт hbarp">hbarp</a>,even you didn't participate in the contest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808817 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808817 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808817"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808753" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DontLookBack" style="position: relative;"> <img src='https://userpic.codeforces.org/1534766/avatar/4eacdc5f9758fc28.jpg'/> </a> <div><a href="/profile/DontLookBack" title="Specialist DontLookBack" class="rated-user user-cyan">DontLookBack</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808753" href="?#comment-808753" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808753" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1534766" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808753"> <div class="moveup"> <div class="ttypography"><p>I am curious, how many div2 testers solved D?</p></div> </div> </div> <div class="reply info"> <a class="comment-808753 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808753 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808753"> <li> <div class="comment"> <table class="comment-table" commentId="808826" commentParentId="808753"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/highonjuice" style="position: relative;"> <img src='https://userpic.codeforces.org/1457566/avatar/f7988dd2af03d38b.jpg'/> </a> <div><a href="/profile/highonjuice" title="Pupil highonjuice" class="rated-user user-green">highonjuice</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808826" href="?#comment-808826" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808753" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808826" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1457566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808826"> <div class="moveup"> <div class="ttypography"><p>like 2 ppl, it was hard for me</p></div> </div> </div> <div class="reply info"> <a class="comment-808826 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808826 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808826"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808757" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tlatoani" style="position: relative;"> <img src='https://userpic.codeforces.org/614001/avatar/598b4e8358aad1b4.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/Tlatoani" title="Grandmaster Tlatoani" class="rated-user user-red">Tlatoani</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:18">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808757" href="?#comment-808757" style="font-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="808757" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="808757" class="CommentVoteFrame" data-commentRating="121" data-commentUserId="614001" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+121</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808757"> <div class="moveup"> <div class="ttypography"><h4>Alternate solution to <a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Инвертируем инверсии</a></h4><p>(Read the first nontrivial paragraph of the editorial before reading this alternate solution)</p><p>Let $$$p_r(k) = x$$$ denote that of the numbers $$$p(1), \ldots, p(r)$$$ in sorted order, $$$p(k)$$$ is equal to the $$$x$$$th of these numbers. We will take a decomposition strategy just as the editorial does, though our strategy will be different. We will divide $$$[1, n]$$$ into blocks of length $$$b$$$. For each block covering some interval $$$[l, r]$$$, we will store $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>This means that for any $$$k$$$, if we know $$$p_r(k)$$$ for some block $$$[l, r]$$$, then we can determine $$$p_{r'}(k)$$$ for the block $$$[l', r']$$$ immediately to the right by binary searching on the numbers stored for $$$[l', r']$$$. Therefore, we can perform queries in $$$O\left(\frac n b \lg b\right)$$$.</p><p>We now need to figure out updates. There are probably simple ways to perform updates in $$$O(b\lg b)$$$, but this yields an overall runtime of $$$O(q\sqrt n \lg n)$$$ which is too slow.</p><p>Therefore, we can instead store each block as a segment tree. For each range $$$[l, r]$$$ in the segment tree we store the same thing we store for the whole block: $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>We then have to quickly merge two intervals. We can merge two intervals of length $$$\lambda$$$ in $$$O(\lambda \lg \lambda)$$$ by doing binary search just as we did above, but this still only yields $$$O(b\lg b)$$$ update overall. However, these $$$\lambda$$$ binary searches can be optimized using two pointers to $$$O(\lambda)$$$, making the overall update $$$O(b)$$$.</p><p>We thus have $$$O\left(\frac n b \lg b\right)$$$ query and $$$O(b)$$$ update. Therefore, we can choose $$$b = \sqrt{n\lg n}$$$ to attain an overall runtime of $$$O\left(q\sqrt{n\lg n}\right)$$$ just as the editorial does.</p><p><a href="https://codeforces.com/contest/1540/submission/120611645">Submission in Kotlin</a></p><p><a href="https://codeforces.com/contest/1540/submission/120612729">Submission in C++</a></p><p>It is interesting to note that this solution is quite fast. At the time of writing this update, the C++ version is the fastest correct submission (and runs under 1 second!) and the Kotlin version is faster than the vast majority of submissions.</p></div> </div> </div> <div class="reply info"> <a class="comment-808757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808757"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808765" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardcode229" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardcode229" title="Newbie hardcode229" class="rated-user user-gray">hardcode229</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808765" href="?#comment-808765" style="font-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="808765" 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="808765" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1635180" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808765"> <div class="moveup"> <div class="ttypography"><p>The 3rd hint for the second problem is same as that of the first problem, is it related or a mistake? <strong>UPD:</strong> it is corrected.</p></div> </div> </div> <div class="reply info"> <a class="comment-808765 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808765 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808765"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808769" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/peanut" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/peanut" title="Specialist peanut" class="rated-user user-cyan">peanut</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:24">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808769" href="?#comment-808769" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808769" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="1167233" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+22</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808769"> <div class="moveup"> <div class="ttypography"><p>speedforces.</p></div> </div> </div> <div class="reply info"> <a class="comment-808769 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808769 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808769"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808781" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/graphs_11" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/graphs_11" title="Specialist graphs_11" class="rated-user user-cyan">graphs_11</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808781" href="?#comment-808781" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808781" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1610110" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808781"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">Problem B Detailed Explanation</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808781 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808781 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808781"> <li> <div class="comment"> <table class="comment-table" commentId="809069" commentParentId="808781"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:40">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809069" href="?#comment-809069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808781" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809069" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809069"> <div class="moveup"> <div class="ttypography"><p>Thank you, very well explained</p></div> </div> </div> <div class="reply info"> <a class="comment-809069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809069"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808790" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PC_E1052" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PC_E1052" title="Pupil PC_E1052" class="rated-user user-green">PC_E1052</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808790" href="?#comment-808790" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808790" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="811219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808790"> <div class="moveup"> <div class="ttypography"><p>c was too easy, d was too hard. but d was very nice problem though. </p></div> </div> </div> <div class="reply info"> <a class="comment-808790 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808790 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808790"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808793" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808793" href="?#comment-808793" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808793" class="CommentVoteFrame" data-commentRating="58" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+58</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808793"> <div class="moveup"> <div class="ttypography"><p>Paging <a class="rated-user user-legendary" href="/profile/ecnerwala" title="Легендарный гроссмейстер ecnerwala"><span class="legendary-user-first-letter">e</span>cnerwala</a> to explain his solution to D1E if he'd like. It seems offline?</p></div> </div> </div> <div class="reply info"> <a class="comment-808793 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808793 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808793"> <li> <div class="comment"> <table class="comment-table" commentId="808979" commentParentId="808793"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ecnerwala" 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/ecnerwala" title="Legendary Grandmaster ecnerwala" class="rated-user user-legendary"><span class="legendary-user-first-letter">e</span>cnerwala</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808979" href="?#comment-808979" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808793" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808979" class="CommentVoteFrame" data-commentRating="40" data-commentUserId="57502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808979"> <div class="moveup"> <div class="ttypography"><p>My solution is $$$O(K N^3 + QN)$$$. I just precomputed the coefficient of each $$$a_i$$$ for each prefix-range for each number of days since person $$$i$$$ becomes positive (only $$$1000$$$ possible days) in $$$O(N \cdot K \cdot N^2)$$$, and then summed up the appropriate ones to answer each query in $$$O(N)$$$. It's written in the offline style to use only $$$O(KN)$$$ memory at a time (grouped by $$$a_i$$$) instead of $$$O(KN^2)$$$.</p><p>My passing submission is just $$$KN^3 / 6$$$ instead of the $$$KN^3$$$ I submitted in contest :'(</p><p>If you guys wanted to prevent this, $$$K$$$ could've been much higher, like $$$1e18$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808979 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808979 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808979"> <li> <div class="comment"> <table class="comment-table" commentId="809002" commentParentId="808979"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809002" href="?#comment-809002" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808979" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809002" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809002"> <div class="moveup"> <div class="ttypography"><p>:( I knew of this solution (it’s why ML is tight) but I didn’t realize that it could be done offline with small memory. Of course $$$K$$$ higher is obvious solution but main issue is that the extra modulos from binary exponentiation make it very hard to pass in Java without allowing other unoptimal solutions through such as precomputing inverses of the matrix. Probably $$$k=10^5$$$ would’ve been a better choice. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-809002 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809002 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809002"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808795" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zukonit14" style="position: relative;"> <img src='https://userpic.codeforces.org/1192187/avatar/5afd49be87fb87d9.jpg'/> </a> <div><a href="/profile/zukonit14" title="Expert zukonit14" class="rated-user user-blue">zukonit14</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808795" href="?#comment-808795" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808795" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1192187" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808795"> <div class="moveup"> <div class="ttypography"><p>Does Div2 D deserved to be D Problem? According to me it should've been Div2 E.</p></div> </div> </div> <div class="reply info"> <a class="comment-808795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808795"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808796" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mangat_angad" style="position: relative;"> <img src='https://userpic.codeforces.org/1449578/avatar/d3cadb0c26e0c11f.jpg'/> </a> <div><a href="/profile/mangat_angad" title="Specialist mangat_angad" class="rated-user user-cyan">mangat_angad</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808796" href="?#comment-808796" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808796" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1449578" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808796"> <div class="moveup"> <div class="ttypography"><p>I feel like such an idiot for not being able to understand problem C (Div2). For some reason I thought the nodes were connected like this — 1-&gt;2-&gt;3-&gt;....-&gt;N and that we had to minimise answer by adding other edges (of negative weight in case they dont give a negative cycle) to this graph.</p></div> </div> </div> <div class="reply info"> <a class="comment-808796 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808796 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808796"> <li> <div class="comment"> <table class="comment-table" commentId="808896" commentParentId="808796"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808896" href="?#comment-808896" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808796" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808896" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808896"> <div class="moveup"> <div class="ttypography"><p>But that's exactly what I did, and the final answer is the sum of the array — sum of all subarrays. <a href="https://codeforces.com/contest/1541/submission/120611950">120611950</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808896 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808896 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808896"> <li> <div class="comment"> <table class="comment-table" commentId="808941" commentParentId="808896"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808941" href="?#comment-808941" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808896" style="font-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="808941" 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="808941" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808941"> <div class="moveup"> <div class="ttypography"><p>No, that's not what you did. To compute the answer via the method described above, you would have to compute how many elements are lesser than the current element at any given iteration and add them and also keep and their count using a Fenwick tree/ BIT. That's the incorrect approach though because sorting would be more optimal.</p></div> </div> </div> <div class="reply info"> <a class="comment-808941 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808941 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808941"> <li> <div class="comment"> <table class="comment-table" commentId="808952" commentParentId="808941"> <tr> <td class="left"> <div style="position: absolute; left: 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/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808952" href="?#comment-808952" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808941" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808952" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808952"> <div class="moveup"> <div class="ttypography"><p>Sorry if I misunderstood things. mangat_angad only mentioned adding negative weighed edges to the 1-&gt;2-&gt;3-&gt;...N graph, which is what I thought to arrive at my solution. The array I mentioned is indeed sorted and formed by distance differences which are the weights in the 1-&gt;2-&gt;3-&gt;...N graph. Unfortunately I'm still too noob to understand the tree structures you mentioned.</p></div> </div> </div> <div class="reply info"> <a class="comment-808952 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808952 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808952"> <li> <div class="comment"> <table class="comment-table" commentId="808955" commentParentId="808952"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808955" href="?#comment-808955" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808952" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808955" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808955"> <div class="moveup"> <div class="ttypography"><p>Nothing unfortunate about it, logic trumps everything </p></div> </div> </div> <div class="reply info"> <a class="comment-808955 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808955 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808955"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808797" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808797" href="?#comment-808797" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808797" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808797"> <div class="moveup"> <div class="ttypography"><p>Just want to apologize to authors for the stupidest question, I misread the task..</p></div> </div> </div> <div class="reply info"> <a class="comment-808797 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808797 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808797"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808813" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808813" href="?#comment-808813" style="font-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="808813" 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="808813" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808813"> <div class="moveup"> <div class="ttypography"><p>Can someone tell me the meaning of this line in problem Div2D/Div1B<br /></p> <blockquote><p>Note that, until reaching, l every possible process still has the same probability of reaching b before a. Therefore, we can assume that the process has reached l and calculate the probability from there.</p> </blockquote><p>What same probability are they talking about?</p></div> </div> </div> <div class="reply info"> <a class="comment-808813 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808813 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808813"> <li> <div class="comment"> <table class="comment-table" commentId="808831" commentParentId="808813"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808831" href="?#comment-808831" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808813" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808831" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808831"> <div class="moveup"> <div class="ttypography"><p>Here's what it's trying to say:</p><p>Suppose we start by marking the root. To mark a or b, we must first mark the lca, so we may assume that the lca has just been marked.</p></div> </div> </div> <div class="reply info"> <a class="comment-808831 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808831 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808831"> <li> <div class="comment"> <table class="comment-table" commentId="808840" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808840" href="?#comment-808840" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808840" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808840"> <div class="moveup"> <div class="ttypography"><p>And what does this line mean? <em>&quot;The problem can be rephrased as having two stacks of size dist(l,a) and dist(l,b) with an arbitrary p to remove a node from one of the two stack (and 1−2p to nothing) and finding the probability that dist(l,b) reaches zero before dist(l,a).&quot;</em></p></div> </div> </div> <div class="reply info"> <a class="comment-808840 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808840 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808840"> <li> <div class="comment"> <table class="comment-table" commentId="808857" commentParentId="808840"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808857" href="?#comment-808857" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808840" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808857" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808857"> <div class="moveup"> <div class="ttypography"><p>Once you've reached the lca $$$l$$$, in a single step you either step closer to $$$a$$$, step closer to $$$b$$$, or step closer to neither.</p></div> </div> </div> <div class="reply info"> <a class="comment-808857 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808857 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808857"> <li> <div class="comment"> <table class="comment-table" commentId="808862" commentParentId="808857"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808862" href="?#comment-808862" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808857" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808862" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808862"> <div class="moveup"> <div class="ttypography"><p>Can you add implementation for this problem please?</p></div> </div> </div> <div class="reply info"> <a class="comment-808862 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808862 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808862"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808849" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808849" href="?#comment-808849" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808849" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808849"> <div class="moveup"> <div class="ttypography"><p>So, we mark lca first (of course). But why wouldn't it affect the final probability of reaching b before a? I mean, why is it sufficient to calculate the probability after marking lca?</p></div> </div> </div> <div class="reply info"> <a class="comment-808849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808849"> <li> <div class="comment"> <table class="comment-table" commentId="808873" commentParentId="808849"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808873" href="?#comment-808873" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808849" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808873" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808873"> <div class="moveup"> <div class="ttypography"><p>Before marking the lca, there is no way to make more progress towards $$$b$$$ than $$$a$$$ or vice versa. The subset of marked vertices also does not change the probability of moving towards $$$a$$$ or $$$b$$$ after reaching the lca because we're choosing uniformly at random and exactly two vertices are of interest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808873 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808873 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808873"> <li> <div class="comment"> <table class="comment-table" commentId="808883" commentParentId="808873"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808883" href="?#comment-808883" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808873" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808883" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808883"> <div class="moveup"> <div class="ttypography"><p>Now I get it. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808883 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808883 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808883"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808814" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808814" href="?#comment-808814" style="font-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="808814" 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="808814" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808814"> <div class="moveup"> <div class="ttypography"><p>So, my Solution for <strong>Div1 Problem B</strong> / <strong>Div2 Problem D</strong> / <strong>1540B — Tree Array</strong>:</p><p>Chose two Nodes $$$A$$$ and $$$B$$$ with $$$A&gt;B$$$. </p><p><strong>First DFS:</strong> Find the path from $$$A$$$ to $$$B$$$. I call it $$$path_p$$$. On $$$path_p$$$ mark the distance to $$$B$$$ for each node. </p><p><strong>Second DFS:</strong> For each remaining node $$$N$$$ find the shortest path to $$$path_p$$$. It will hit it at some node of the $$$path_p$$$ which has some distance $$$D$$$ marked on it. We mark $$$N$$$ with $$$D$$$. (See comment below for image.)</p><p><strong>Calculation:</strong> For each node $$$N$$$ we can calculate $$$P_i$$$. $$$P_i$$$ is the probability to reach Node $$$B$$$ before we reach Node $$$A$$$. We sum $$$P_i$$$ for each node. $$$P_i$$$ is also the probability, that the pair of Nodes $$$A$$$ and $$$B$$$ with starting node $$$N$$$ will contribute to the inversion sum. </p><p><strong>Iteration:</strong> We need to repeat this for each pair $$$A$$$ and $$$B$$$. In the end we divide the answer by $$$n$$$, the amount of nodes (the probability to start with Node $$$N$$$). </p><p>This algorithm is $$$O(N^3)$$$. See my Solution <a href="/contest/1540/submission/120603369" title="Посылка 120603369 от OleschY">120603369</a></p> <div class="spoiler"><b class="spoiler-title">How to calculate P_i</b><div class="spoiler-content" style="display: none;"><p>I wrote myself a small helper DP-program to find the regularities. Let $$$D$$$ be the Distance between $$$A$$$ and $$$B$$$ and $$$d$$$ be the distance from the node $$$N$$$ to $$$B$$$. My educated guess was: $$$P_i=\frac{\sum_{i=0}^{d-1}\binom{D-1}{i} }{2^{D-1}}$$$</p> <div class="spoiler"><b class="spoiler-title">Helper Program</b><div class="spoiler-content" style="display: none;"><p>It checks for a path of some length for each Intervall $$$[A,B]$$$ which is already visited, what the probability to reach one node before the other is. </p> <pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; int solve(int n) { vector&lt;vector&lt;double&gt;&gt; dp(n, vector&lt;double&gt;(n, 0)); for(int i = 0; i &lt; n; ++i) { dp[0][i] = 1; dp[i][n - 1] = 0; } dp[0][n - 1] = -1; for(int w = n; w &gt;= 0; w--) { for(int i = 1; i + w &lt; n - 1; i++) { int l = i; int r = w + i; dp[l][r] = 0.5 * (dp[l - 1][r] + dp[l][r + 1]); } } cout &lt;&lt; n &lt;&lt; &quot;\n\n&quot;; for(int i = 0; i &lt; n; i++) { cout &lt;&lt; dp[i][i]*(1&lt;&lt;(n-2)) &lt;&lt; &quot;\n&quot;; } cout &lt;&lt; &quot;\n\n\n\n&quot;; return 0; } //====================== // Technical stuff //====================== int main() { int ntest = 12; for(int test = 2; test &lt; ntest; ++test) { solve(test); } return 0; } </code></pre></div></div></div></div></div> </div> </div> <div class="reply info"> <a class="comment-808814 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808814 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808814"> <li> <div class="comment"> <table class="comment-table" commentId="808843" commentParentId="808814"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808843" href="?#comment-808843" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808814" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808843" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808843"> <div class="moveup"> <div class="ttypography"><p>Can you explain your solution in a little bit more detail? :')</p></div> </div> </div> <div class="reply info"> <a class="comment-808843 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808843 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808843"> <li> <div class="comment"> <table class="comment-table" commentId="808869" commentParentId="808843"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808869" href="?#comment-808869" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808843" style="font-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="808869" 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="808869" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808869"> <div class="moveup"> <div class="ttypography"><p>Oof, I can give you an image, that shows how the distances from the two DFS are distributed on an example. You can see Nodes $$$A$$$ and $$$B$$$ and the numbers are the distances we write into the nodes. </p><p><img alt=" " src="/predownloaded/d8/2f/d82f98ecd2c1b4bd15b3c40e62476f6ae2741a64.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>If you have specific questions about some steps go ahead and ask. </p></div> </div> </div> <div class="reply info"> <a class="comment-808869 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808869 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808869"> <li> <div class="comment"> <table class="comment-table" commentId="810069" commentParentId="808869"> <tr> <td class="left"> <div style="position: absolute; left: 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/Mrajaryan" style="position: relative;"> <img src='https://userpic.codeforces.org/1377953/avatar/e904b3a3a2eac1ad.jpg'/> </a> <div><a href="/profile/Mrajaryan" title="Newbie Mrajaryan" class="rated-user user-gray">Mrajaryan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 15:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810069" href="?#comment-810069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808869" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810069" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1377953" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810069"> <div class="moveup"> <div class="ttypography"><p>what does the dp states mean in your helper program? I am unable to understand. Can you please explain?</p></div> </div> </div> <div class="reply info"> <a class="comment-810069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810069"> <li> <div class="comment"> <table class="comment-table" commentId="810097" commentParentId="810069"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 18:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810097" href="?#comment-810097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-810069" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810097"> <div class="moveup"> <div class="ttypography"><p>You have Nodes $$$1$$$ through $$$N$$$, neighbouring IDs are connected. The state $$$dp[l][r]$$$ is the probability, that node $$$N$$$ will be reached before node $$$1$$$ with all the nodes $$$l$$$ through $$$r$$$ marked already. Obviously $$$dp[1][x]=0$$$ and $$$dp[x][N]=1$$$ ($$$dp[1][N]$$$ can't happen). The recurrence is $$$dp[l][r]=(dp[l-1][r]+dp[l][r+1])/2$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-810097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808818" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808818" href="?#comment-808818" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808818" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808818"> <div class="moveup"> <div class="ttypography"><p>I can't grasp the editorial of Div 2 D/ Div 1 B. Can somebody provide a more intuitive explanation?</p></div> </div> </div> <div class="reply info"> <a class="comment-808818 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808818 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808818"> <li> <div class="comment"> <table class="comment-table" commentId="808821" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:45">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808821" href="?#comment-808821" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808821" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808821"> <div class="moveup"> <div class="ttypography"><p>same :(</p></div> </div> </div> <div class="reply info"> <a class="comment-808821 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808821 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808821"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808861" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808861" href="?#comment-808861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808861" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808861"> <div class="moveup"> <div class="ttypography"><p>Step 1. use linearity of expectation. The answer is</p> <center>$$$\sum_{a&lt;b} P(b\text{ appears before }a). $$$</center><p>Step 2: Observe that if we start by marking a vertex $$$c$$$ on the path between $$$a$$$ and $$$b$$$, and suppose the next marked vertex on the path is $$$d$$$. Then, the probability that $$$d$$$ is between $$$c$$$ and $$$a$$$ and the probability that $$$d$$$ is between $$$c$$$ and $$$b$$$ are both $$$1/2$$$. This is because there are only two choices for $$$d$$$ and we're choosing uniformly at random. This means that the answer only depends on $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p><p>Step 3: run a dp to calculate the probability that we mark $$$b$$$ before $$$a$$$ given $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808861"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808833" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808833" href="?#comment-808833" style="font-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="808833" 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="808833" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-72" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-72</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808833"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin &gt;&gt; t; while(t--){ int n; cin &gt;&gt; n; long long arr[n]; for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0; for(int i = 0; i &lt; n — 1; i++){ for(int j = arr[i] — 2 — i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } } } cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;; } return 0; }</p><p>/* Accepted code A different approach using arrays (as I don't know what vectors are, haven't read that) I hope this is a optimal approach. Any suggestions related to this are whole-heartedly welcomed. Also, please guide me how could I have optimized the code to a much extent. Thanks in advance! Keep programming! */</p></div> </div> </div> <div class="reply info"> <a class="comment-808833 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808833 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808833"> <li> <div class="comment"> <table class="comment-table" commentId="808844" commentParentId="808833"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808844" href="?#comment-808844" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808833" style="font-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="808844" 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="808844" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-35" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808844"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-808844 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808844 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808844"> <li> <div class="comment"> <table class="comment-table" commentId="808863" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808863" href="?#comment-808863" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808863" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808863"> <div class="moveup"> <div class="ttypography"><p>Not studied yet, I'm still a beginner, but planning to start soon. Thanks for the guidance.</p></div> </div> </div> <div class="reply info"> <a class="comment-808863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808863"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808879" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808879" href="?#comment-808879" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808879" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808879"> <div class="moveup"> <div class="ttypography"><p>once upon a time, I also did problems while not know what vectors are. sad times :'(</p></div> </div> </div> <div class="reply info"> <a class="comment-808879 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808879 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808879"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808926" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808926" href="?#comment-808926" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808926" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808926"> <div class="moveup"> <div class="ttypography"><p>There's no issue in not knowing vectors. Yes they are important I agree but not knowing vectors should not be discouraged. I became expert here without knowing anything about vectors plus he is a beginner so he shouldn't be discouraged like this.</p></div> </div> </div> <div class="reply info"> <a class="comment-808926 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808926 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808926"> <li> <div class="comment"> <table class="comment-table" commentId="808927" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Tech.Maniac" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Tech.Maniac" title="Expert Tech.Maniac" class="rated-user user-blue">Tech.Maniac</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808927" href="?#comment-808927" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808927" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1242860" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808927"> <div class="moveup"> <div class="ttypography"><p>+1, I agree with you. Same I was expert last year solely using arrays</p></div> </div> </div> <div class="reply info"> <a class="comment-808927 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808927 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808927"> <li> <div class="comment"> <table class="comment-table" commentId="809201" commentParentId="808927"> <tr> <td class="left"> <div style="position: absolute; left: 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/Yash.Amin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Yash.Amin" title="Specialist Yash.Amin" class="rated-user user-cyan">Yash.Amin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809201" href="?#comment-809201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808927" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809201" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-28" data-commentUserId="1226462" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-28</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809201"> <div class="moveup"> <div class="ttypography"><p>Bas kar bsdk kitna jhooth bolega</p></div> </div> </div> <div class="reply info"> <a class="comment-809201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809201"> <li> <div class="comment"> <table class="comment-table" commentId="809215" commentParentId="809201"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809215" href="?#comment-809215" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809215" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809215"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-blue" href="/profile/Yash.Amin" title="Эксперт Yash.Amin">Yash.Amin</a> Could you please refrain from using foul language on educational discussions. Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-809215 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809215 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809215"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808928" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808928" href="?#comment-808928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808928" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808928"> <div class="moveup"> <div class="ttypography"><p>Ah my bad, I did not want to come across as being arrogant, but I was genuinely confused that some people did not know vectors although they are using C++.</p></div> </div> </div> <div class="reply info"> <a class="comment-808928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808928"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808839" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamkiller04" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dreamkiller04" title="Newbie dreamkiller04" class="rated-user user-gray">dreamkiller04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808839" href="?#comment-808839" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2089608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808839"> <div class="moveup"> <div class="ttypography"><p>Please add implementations too.</p></div> </div> </div> <div class="reply info"> <a class="comment-808839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808839"> <li> <div class="comment"> <table class="comment-table" commentId="809106" commentParentId="808839"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809106" href="?#comment-809106" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808839" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809106" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809106"> <div class="moveup"> <div class="ttypography"><p>Simply running two loops and checking every case would give a TLE. So, we might want to minimize the number of operations. For this, we would only consider the cases where the sum of indices is a multiple of an element.</p><p>For this, we would first create two loops, one within the other, first loop iterating i from 0 to (n — 1) with an incrementation of 1. By observation, we can see that the first index for which the sum of indices will be a multiple of arr[i] is (arr[i] — 2 — i).</p><p>So, in the nested loop we will run j = (arr[i] — 2 — i) till (n — 1) with an incrementation of arr[i]. We would ignore the cases where j &lt; 0 or j &gt;= n.</p><p>Finally, we need to check for how many cases this holds (arr[i] * arr[j] = i + j + 2 and j &gt; i).</p><p>Suggestions are welcomed!</p></div> </div> </div> <div class="reply info"> <a class="comment-809106 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809106 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809106"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808842" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808842" href="?#comment-808842" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808842" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-64" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-64</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808842"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){</p><p>ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);</p><p>int t;</p><p>cin &gt;&gt; t;</p><p>while(t--){</p><p>int n;</p> <pre>cin &gt;&gt; n;</pre><p>long long arr[n];</p> <pre>for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0;</pre><p>for(int i = 0; i &lt; n — 1; i++){</p> <pre>for(int j = arr[i] &amp;mdash; 2 &amp;mdash; i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } }</pre><p>}</p><p>cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;;</p><p>}</p> <pre>return 0;</pre><p>}</p><p>/* Accepted code</p><p>A different approach using arrays (as I don't know what vectors are, haven't read that)</p><p>I hope this is a optimal approach.</p><p>Any suggestions related to this are whole-heartedly welcomed.</p><p>Also, please guide me how could I have optimized the code to a much extent.</p><p>Thanks in advance!</p><p>Keep programming! </p><p>*/</p></div> </div> </div> <div class="reply info"> <a class="comment-808842 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808842 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808842"> <li> <div class="comment"> <table class="comment-table" commentId="808851" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808851" href="?#comment-808851" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808851" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808851"> <div class="moveup"> <div class="ttypography"><p>Use spoilers for writing codes, please!</p></div> </div> </div> <div class="reply info"> <a class="comment-808851 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808851 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808851"> <li> <div class="comment"> <table class="comment-table" commentId="808870" commentParentId="808851"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808870" href="?#comment-808870" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808851" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808870" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808870"> <div class="moveup"> <div class="ttypography"><p>Actually, this is my first comment. Don't know much of this stuff as of now, but I'll surely take care of it the very next time.</p></div> </div> </div> <div class="reply info"> <a class="comment-808870 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808870 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808870"> <li> <div class="comment"> <table class="comment-table" commentId="809760" commentParentId="808870"> <tr> <td class="left"> <div style="position: absolute; left: 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/sus" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sus" title="Pupil sus" class="rated-user user-green">sus</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 05:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809760" href="?#comment-809760" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808870" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809760" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1749651" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809760"> <div class="moveup"> <div class="ttypography"><p>what problem is your code for</p></div> </div> </div> <div class="reply info"> <a class="comment-809760 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809760 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809760"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808884" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sevlll777" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sevlll777" title="Grandmaster sevlll777" class="rated-user user-red">sevlll777</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808884" href="?#comment-808884" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808884" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="839333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808884"> <div class="moveup"> <div class="ttypography"><p>NICE CODESTYLE!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-808884 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808884 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808884"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809084" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cj2021" style="position: relative;"> <img src='https://userpic.codeforces.org/1927237/avatar/b64ff59bd9dcf385.jpg'/> </a> <div><a href="/profile/cj2021" title="Newbie cj2021" class="rated-user user-gray">cj2021</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809084" href="?#comment-809084" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809084" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1927237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809084"> <div class="moveup"> <div class="ttypography"><p>What is &amp;mdash?</p><p>Just curious to know as haven't seen it before.</p></div> </div> </div> <div class="reply info"> <a class="comment-809084 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809084 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809084"> <li> <div class="comment"> <table class="comment-table" commentId="809097" commentParentId="809084"> <tr> <td class="left"> <div style="position: absolute; left: 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/klahsiv" style="position: relative;"> <img src='https://userpic.codeforces.org/1590145/avatar/1bf86ae3d48e55b.jpg'/> </a> <div><a href="/profile/klahsiv" title="Expert klahsiv" class="rated-user user-blue">klahsiv</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809097" href="?#comment-809097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809084" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590145" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809097"> <div class="moveup"> <div class="ttypography"><p>it is minus (-).</p></div> </div> </div> <div class="reply info"> <a class="comment-809097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808848" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/willy108" style="position: relative;"> <img src='https://userpic.codeforces.org/1439320/avatar/d7f79ed4e8b32e9a.jpg'/> </a> <div><a href="/profile/willy108" title="Master willy108" class="rated-user user-orange">willy108</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808848" href="?#comment-808848" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808848" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="1439320" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808848"> <div class="moveup"> <div class="ttypography"><p>Div2 B can also be done in O(NsqrtN). We know that for a given pair of indeces i+j &lt; 2n, so any pair that a[i] * a[j] &lt; 2n will have to have one of the two terms be &lt;= sqrt(n) (with some off by one errors of course). So the algorithm is to store an array of pairs [array value, index] and sort that array by the value. If the array value is &lt;= sqrt(2n) we can naively loop over the rest of the array in O(n) time and check (be careful about overcount), and if the value is &gt; sqrt(n), we can ignore it. This works since when a[i] * a[j] &lt; 2n one of a[i] or a[j] has to be &lt;= sqrt(2n) and as a result, every pair will be counted.</p></div> </div> </div> <div class="reply info"> <a class="comment-808848 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808848 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808848"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808860" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bcollet" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bcollet" title="Master bcollet" class="rated-user user-orange">bcollet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808860" href="?#comment-808860" style="font-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="808860" 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="808860" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="858059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808860"> <div class="moveup"> <div class="ttypography"><p>I don't understand in div1 C why it's prefix of b, in the case i=3 we have $$$a_1+a_2+a_3=f_1+f_1+b_1+f_1+b_1+b_2$$$ so $$$f_1=(ap_i-2b_1-b_2)$$$ I believe the general formula is something in the taste of $$$f_1=(ap_i-ibp_{i-1}+bpt_{i-1})/i$$$ where bpt_i=b_1+2b_2+...+ib_i, I think I miss something<br />Edit: corrected</p></div> </div> </div> <div class="reply info"> <a class="comment-808860 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808860 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808860"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808865" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ParsaS" style="position: relative;"> <img src='https://userpic.codeforces.org/1590150/avatar/dc2d8c002d2c5e1e.jpg'/> </a> <div><a href="/profile/ParsaS" title="Candidate Master ParsaS" class="rated-user user-violet">ParsaS</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808865" href="?#comment-808865" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808865" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590150" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808865"> <div class="moveup"> <div class="ttypography"><p>Nice problems. thanks for almost fast editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-808865 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808865 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808865"> <li> <div class="comment"> <table class="comment-table" commentId="808871" commentParentId="808865"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/E404_Not_Found" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/E404_Not_Found" title="Expert E404_Not_Found" class="rated-user user-blue">E404_Not_Found</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808871" href="?#comment-808871" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808865" style="font-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="808871" 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="808871" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1662858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808871"> <div class="moveup"> <div class="ttypography"><p>Yes thanks for fast editorial :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808871 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808871 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808871"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808890" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vikash_8090_b" style="position: relative;"> <img src='https://userpic.codeforces.org/1969032/avatar/a0f23c893ae54e74.jpg'/> </a> <div><a href="/profile/vikash_8090_b" title="Newbie vikash_8090_b" class="rated-user user-gray">vikash_8090_b</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808890" href="?#comment-808890" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808890" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="1969032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808890"> <div class="moveup"> <div class="ttypography"><p>is there anyone who can't even solve one question of today's contest ..</p></div> </div> </div> <div class="reply info"> <a class="comment-808890 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808890 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808890"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808892" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808892" href="?#comment-808892" style="font-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="808892" 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="808892" class="CommentVoteFrame" data-commentRating="-6" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808892"> <div class="moveup"> <div class="ttypography"><p>Deleted :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808892 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808892 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808892"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808918" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prituladima" style="position: relative;"> <img src='https://userpic.codeforces.org/116750/avatar/ca46d0256a294b26.jpg'/> </a> <div><a href="/profile/prituladima" title="Pupil prituladima" class="rated-user user-green">prituladima</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808918" href="?#comment-808918" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808918" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="116750" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808918"> <div class="moveup"> <div class="ttypography"><p>Please explain div2c/div1a problem a little bit more. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808918 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808918 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808918"> <li> <div class="comment"> <table class="comment-table" commentId="808921" commentParentId="808918"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808921" href="?#comment-808921" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808918" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808921" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808921"> <div class="moveup"> <div class="ttypography"><p>Try out this <a href="https://youtube.com/c/MagentaCobra">channel</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808921 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808921 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808921"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808950" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jakab922" style="position: relative;"> <img src='https://userpic.codeforces.org/53532/avatar/f9515e974f3ebcb1.jpg'/> </a> <div><a href="/profile/jakab922" title="Specialist jakab922" class="rated-user user-cyan">jakab922</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808950" href="?#comment-808950" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808950" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="53532" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808950"> <div class="moveup"> <div class="ttypography"><p>I don't really understand the need for a recursive function for the stack emptying probabilities in <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a>. I mean given that you have a stack of size <code>n</code> and and <code>m</code> you can basically have an array of size <code>n + m</code> filled with <code>0</code>s and <code>1</code>s where <code>0</code> at the <code>i</code>th place means that the <code>i</code>th element was taken from the first stack. Any such array which has <code>n</code> <code>0</code>s and <code>m</code> <code>1</code>s correspond to one process and it's easy to see that whoever takes the last spot in the array gets emptied later which gives an easy way to calculate the probabilities. Namely $$$\binom{n + m - 1}{n - 1} / \binom{n + m}{n}$$$ for the first and similar to the other. </p></div> </div> </div> <div class="reply info"> <a class="comment-808950 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808950 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808950"> <li> <div class="comment"> <table class="comment-table" commentId="808959" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cuom1999" style="position: relative;"> <img src='https://userpic.codeforces.org/253776/avatar/934152bc42a0b10c.jpg'/> </a> <div><a href="/profile/cuom1999" title="Grandmaster cuom1999" class="rated-user user-red">cuom1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808959" href="?#comment-808959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="253776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808959"> <div class="moveup"> <div class="ttypography"><p>If $$$m=2$$$ and $$$n=1$$$, your approach gives $$$\frac{1}{3}$$$. The correct answer should be $$$\frac{1}{4}$$$. </p><p>P/S: I'm also curious if there is any combinatoric approach for this,<a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808959"> <li> <div class="comment"> <table class="comment-table" commentId="809004" commentParentId="808959"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809004" href="?#comment-809004" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809004" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809004"> <div class="moveup"> <div class="ttypography"><p>I would guess that there’s no easy closed form. You can evaluate in $$$O(n)$$$ however by counting right up paths from $$$(a,0)$$$ to $$$(x,y)$$$ for all $$$a$$$ and multiplying by $$$2^{-steps}$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-809004 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809004 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809004"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809366" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/geekpradd" style="position: relative;"> <img src='https://userpic.codeforces.org/367430/avatar/427394aa7f5a63a0.jpg'/> </a> <div><a href="/profile/geekpradd" title="Candidate Master geekpradd" class="rated-user user-violet">geekpradd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809366" href="?#comment-809366" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809366" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="367430" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809366"> <div class="moveup"> <div class="ttypography"><p>The problem with this is that all the possibilities are not equilikely, consider $$$m=2, n=1$$$ and let $$$1$$$ denote entries from the stack of size $$$n$$$. Then the probability of obtaining $$$100$$$ is $$$1/2$$$, while obtaining $$$010$$$ and $$$001$$$ has a probability of $$$1/4$$$. Your approach assumes a uniform prior probability (in which case the answer is indeed $$$1/3$$$ whereas here it is $$$1/4$$$ which is the probability of getting $$$001$$$)</p></div> </div> </div> <div class="reply info"> <a class="comment-809366 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809366 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809366"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thunderboltz" style="position: relative;"> <img src='https://userpic.codeforces.org/1170396/avatar/4f017b259605bc5c.jpg'/> </a> <div><a href="/profile/thunderboltz" title="Newbie thunderboltz" class="rated-user user-gray">thunderboltz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808951" href="?#comment-808951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170396" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808951"> <div class="moveup"> <div class="ttypography"><p>Problem Div2C/Div1A, Plz somebody explain 3rd hint. I didn't get why this condition must be true </p><p><code>The sum of the values of edges with positive weight must be ≥ the maximum value in the array.</code></p></div> </div> </div> <div class="reply info"> <a class="comment-808951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808951"> <li> <div class="comment"> <table class="comment-table" commentId="808995" commentParentId="808951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808995" href="?#comment-808995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808995" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808995"> <div class="moveup"> <div class="ttypography"><p>I like to think about C this way: The cheapest node is the root, and the most expensive node, X, is the one with the highest value, D. Therefore no matter how we make our edges, we need at least 1 path from node to X with distance D. So let's build 1 single edge of positive weight from 1 to X with weight D.</p><p>Now from node X, all other nodes are &lt;= D. We can use negative edges to go there. Now the problem just becomes &quot;assign as many negative edges as possible&quot; to the rest of the nodes. </p></div> </div> </div> <div class="reply info"> <a class="comment-808995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808995"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808971" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808971" href="?#comment-808971" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808971" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808971"> <div class="moveup"> <div class="ttypography"><p>In problem <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a> I agree with everything up to:</p> <blockquote><p>Once l is reached, we now note that the probability that the process &quot;gets closer&quot; to b is always equal to the probability of getting closer to a.</p> </blockquote><p>I agree with this quote if it was about each individual set of marked nodes and single step for them. Because for any individual set of marked nodes, those probabilities is just one over the number of options at the moment. But I don't understand why I should forget about everything else what happens with other parts of tree, because after single step which is neither towards <strong>a</strong> neither towards <strong>b</strong>, the number of options (nodes we can mark on next step) may change.</p></div> </div> </div> <div class="reply info"> <a class="comment-808971 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808971 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808971"> <li> <div class="comment"> <table class="comment-table" commentId="809006" commentParentId="808971"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809006" href="?#comment-809006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808971" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809006" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809006"> <div class="moveup"> <div class="ttypography"><p>That is correct, but to see how it stays the same you can think of it inductively. Use strong induction and assume probability is the same no matter what the state of the tree is. Then from $$$(x,y)$$$ you always have an equal probability of ending up in one of the two states you can transition to because $$$p$$$ is always the same. Every scenario you enter one state, there’s another scenario with the same probability that enters the other state. So, the probability of entering one of the two states is the same as the other, thus $$$0.5$$$. Hopefully that makes things more clear.</p></div> </div> </div> <div class="reply info"> <a class="comment-809006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809006"> <li> <div class="comment"> <table class="comment-table" commentId="809113" commentParentId="809006"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809113" href="?#comment-809113" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809006" style="font-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="809113" 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="809113" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809113"> <div class="moveup"> <div class="ttypography"><p>Oh thanks, it's clear now. So, base of induction is when only <strong>l</strong> reached, and we can show that probability to make step towards <strong>a</strong> and <strong>b</strong> is same because for each individual set you can go from <strong>l</strong> to <strong>b</strong> instead of going from <strong>l</strong> into <strong>a</strong>, using exactly same steps in between (those steps which doesn't change distances to <strong>a</strong> and <strong>b</strong>). And similar holds for next steps.</p></div> </div> </div> <div class="reply info"> <a class="comment-809113 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809113 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809113"> <li> <div class="comment"> <table class="comment-table" commentId="821713" commentParentId="809113"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 08:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821713" href="?#comment-821713" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809113" style="font-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="821713" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="821713" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-821713"> <div class="moveup"> <div class="ttypography"><p>Can you explain this?</p><p>Assume $$$X$$$ is initially node we chose. Then define a function $$$g$$$ :</p><p>$$$g[a][b][STATE]$$$ = probability to reach a before b while state of the tree we reach is $$$STATE$$$, and $$$a$$$, $$$b$$$ is length of path.</p><p><img alt=" " src="/predownloaded/c2/32/c232d053fe3fbd1dedc06e56db58a7c139157987.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>follow the image, I can see : $$$g[a][b][STATE_x] = \frac{1}{4} (g[a][b][STATE_d] + g[a][b][STATE_e] + g[a — 1][b][closer_a] + g[a][b — 1][closer_b])$$$</p><p>It can easy see that the probability can change. Or I wrong in some where?</p></div> </div> </div> <div class="reply info"> <a class="comment-821713 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821713 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821713"> <li> <div class="comment"> <table class="comment-table" commentId="821861" commentParentId="821713"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 18:25">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821861" href="?#comment-821861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821713" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="821861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-821861"> <div class="moveup"> <div class="ttypography"><p>I'll hide my long explanation under spoiler</p> <div class="spoiler"><b class="spoiler-title">horrible wall of text</b><div class="spoiler-content" style="display: none;"><p>To put things into words, I want to define some things. First, suppose we marked some $$$s_1, s_2, s_3 ... s_k$$$ vertices in exact this order. Then, let $$$P(s)$$$ to be probability to mark them in this sequence. It can be decomposed into $$$P(s) = p_1 \cdot p_2 \cdot p_3 \cdot ... \cdot p_k$$$ where $$$p_i = 1/o_{i-1}$$$ where $$$o_i$$$ is number of options at step $$$i$$$ — number of opened vertices, except $$$p_0 = 1/n$$$, or $$$o_0 = n$$$.</p><p>Then, let $$$l = LCA(a, b)$$$ where $$$LCA$$$ is lowest common ancestor. Then, let $$$x_v$$$ to be some sort of 'cost'. For each $$$v$$$ on path between $$$a$$$ and $$$l$$$ it will be distance to $$$l$$$, and $$$-1$$$ everywhere else. Similarly, for each $$$v$$$ on path between $$$b$$$ and $$$l$$$ let $$$y_v$$$ to be distance to $$$l$$$ and $$$-1$$$ everywhere else. Let</p> <center>$$$ A(s) = \max\limits_{v\in s}x_v \\ B(s) = \max\limits_{v\in s}y_v $$$</center><p>Then $$$A(s)$$$ is equal to how far we reach $$$a$$$, and $$$B(s)$$$ is equal to how far we reach $$$b$$$. Let say we are in situation $$$(A(s), B(s))$$$ after marking $$$s$$$, and therefore situation is pair of numbers. Situation $$$(-1,-1)$$$ corresponds that no vertex is marked on path from $$$a$$$ to $$$b$$$. Situation $$$(0,0)$$$ corresponds to only $$$l$$$ marked on path from $$$a$$$ to $$$b$$$. And situation $$$(1,0)$$$ corresponds to $$$l$$$ and single vertex towards $$$a$$$ is marked.</p><p>Finally, let say sequence of marks $$$s$$$ reached state $$$(A(s), B(s))$$$ if either $$$A(s) = x_{s_k}$$$ or $$$B(s) = y_{s_k}$$$, in other words, last vertex is on path from $$$a$$$ to $$$b$$$ and it did change situation.</p><p>Now, what we want to prove is following:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha+1,\beta)} P(s) = \sum\limits_{s\;reached\;(\alpha,\beta+1)} P(s)$$$</center><p><strong>For some fixed</strong> $$$s_1$$$, which is root we chosen. And the way we prove it is that $$$s$$$ that is reached $$$(\alpha+1,\beta)$$$ consists of $$$u$$$ that reached $$$(\alpha,\beta)$$$ plus additional steps: $$$w$$$ plus $$$s_k$$$. So $$$s = u..w..s_k$$$ where $$$..$$$ is concatenation. It's easy to see what none of vertices from $$$w$$$ is on path from $$$a$$$ to $$$b$$$. Also, it's easy to see that we could instead of choosing $$$s_k$$$ could choose vertex $$$z$$$ towards $$$b$$$, and it would have same probability. In other words $$$P(s) = P(u..w..z)$$$. And this $$$u..w..z$$$ should reach state $$$(\alpha, \beta+1)$$$. So it should be in right side sum of our equation we want to prove.</p><p>So, for any $$$s$$$ from left sum, we can make $$$s'$$$ from right sum in unique way, and it will have same $$$P(s) = P(s')$$$. Similarly, for any $$$s$$$ from right sum, we can make $$$s'$$$ from left sum in unique way, and it will have same $$$P(s) = P(s')$$$. So this is bijection, and each element from left sum corresponds to element from right sum with same value, so those sums should have same value. Therefore it's equality.</p><p>Initially I wanted to trim $$$s$$$ from $$$(\alpha+1,\beta)$$$ to $$$(\alpha,\beta)$$$ and show similar thing based on following sum:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha,\beta)} P(s)$$$</center><p>Which is probability to reach state $$$(\alpha, \beta)$$$, but luckily it didn't required. I'll use notation $$$P(reach(\alpha, \beta))$$$ for this probability.</p><p>Thing that is not covered though: why this equality can be translated into probability $$$= 1/2$$$? Well, from $$$(\alpha, \beta)$$$ you eventually will reach either $$$(\alpha+1,\beta)$$$ or $$$(\alpha,\beta+1)$$$, so you can see this as example of Law of total probability. $$$P(reach(\alpha, \beta)) = P(reach (\alpha+1, \beta)) + P(reach (\alpha, \beta+1))$$$, because events $$$(\alpha+1,\beta)$$$ and $$$(\alpha,\beta+1)$$$ are disjoint events given $$$(\alpha, \beta)$$$ is reached. And we proved they have equal probability so $$$P(reach(\alpha, \beta)) = 2\cdot P(reach (\alpha+1, \beta))$$$, so $$$P(reach (\alpha+1, \beta)) = 1/2\cdot P(reach(\alpha, \beta))$$$ which we actually use.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-821861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821861"> <li> <div class="comment"> <table class="comment-table" commentId="822027" commentParentId="821861"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/28/2021 13:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822027" href="?#comment-822027" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821861" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="822027" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822027"> <div class="moveup"> <div class="ttypography"><p>Oh, sorry, there is one missing part. We proved $$$P(reached(\alpha+1,\beta))=P(reached(\alpha,\beta+1))$$$ <strong>given</strong> $$$(\alpha,\beta)$$$ is reached, but this is actually what we need. This <strong>given</strong> condition is what I missed. Without <strong>given</strong> we could reach $$$(\alpha+1,\beta)$$$ from reaching $$$(\alpha+1,\beta-1)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-822027 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822027 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822027"> <li> <div class="comment"> <table class="comment-table" commentId="822370" commentParentId="822027"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 13:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822370" href="?#comment-822370" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822027" style="font-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="822370" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="822370" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822370"> <div class="moveup"> <div class="ttypography"><p>Thanks for amz explain. I realize that I had some missunderstand in the way we calc $$$P(reach\ A\ before\ B)$$$</p><p>This's exactly what in my mind one day ago: let $$$s = ...a...b...$$$ where $$$a$$$ and $$$b$$$ is node $$$a$$$ and node $$$b$$$, &quot;$$$...$$$&quot; mean some node between them which we chose them in exactly that order, or in other word, $$$s$$$ is state represent what we chose (exact in this order) I think $$$P(reach\ A\ before\ B)$$$ (or $$$P(A&lt;B)$$$) must be calculate in this way :</p><p>$$$P(A&lt;B) = \sum_{\substack{all\ s\ which\ a&lt;b}} P(s)$$$</p><p>But unfortunately, it's wrong (may be, or I still missunderstanding)</p><p>$$$P(A) = \sum_{\substack{all\ B[i]\ \subseteq\ A}} P(B[i])$$$ if and only if all $$$B[i]$$$ are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-822370 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822370 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822370"> <li> <div class="comment"> <table class="comment-table" commentId="822755" commentParentId="822370"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 22:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822755" href="?#comment-822755" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822370" style="font-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="822755" 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="822755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822755"> <div class="moveup"> <div class="ttypography"><p>$$$P(A &lt; B)$$$ in your terms is exactly what we need (if a = A and b = B).</p><p>I don't understand last formula, everything else looks fine.</p><p>And to find $$$P(A &lt; B)$$$ we use fact above and calculate all possible ways to reach $$$a$$$ earlier than $$$b$$$ we use $$$(\alpha, \beta)$$$ states using my notation: you either get $$$\alpha$$$ equal to dist to $$$a$$$ when $$$\beta$$$ = 0, or $$$\beta$$$ = 1, or 2, or 3...</p> <center>$$$ P(A &lt; B) = \\ =\sum\limits_{i=0}^{dist(b,l)}P(reach(dist(a,l),i)\;given\; reached(dist(a,l)-1,i)) \\ = \sum\limits_{i=0}^{dist(b,l)}P(reached(dist(a,l)-1,i))\cdot \frac{1}{2} $$$</center><p>Or you can rephrase task into other task with two kind of balls. What probability to remove all balls of one kind earlier than other, if you pick one or other kind of ball with probability 1/2.</p></div> </div> </div> <div class="reply info"> <a class="comment-822755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822755"> </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="808983" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/xsc" style="position: relative;"> <img src='https://userpic.codeforces.org/343/avatar/9eaf243b1eb8c3d4.jpg'/> </a> <div><a href="/profile/xsc" title="Specialist xsc" class="rated-user user-cyan">xsc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808983" href="?#comment-808983" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808983" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="343" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808983"> <div class="moveup"> <div class="ttypography"><p>Div2 D, O(N^4) solution <a href="/contest/1541/submission/120623566" title="Посылка 120623566 от xsc">120623566</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808983 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808983 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808983"> <li> <div class="comment"> <table class="comment-table" commentId="809278" commentParentId="808983"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DavidXu_JJ" style="position: relative;"> <img src='https://userpic.codeforces.org/2003708/avatar/623dc8036b4e9d72.jpg'/> </a> <div><a href="/profile/DavidXu_JJ" title="Expert DavidXu_JJ" class="rated-user user-blue">DavidXu_JJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809278" href="?#comment-809278" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808983" style="font-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="809278" 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="809278" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2003708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809278"> <div class="moveup"> <div class="ttypography"><p>Your code really helps me a lot in debugging,thanks.</p><p>By the way,it's weired that I get Wrong6 when I try to optimize to O(N^3*logN) by binary search on tree.</p><p>I have tested my function on other online judge and my function seems to be correct.</p></div> </div> </div> <div class="reply info"> <a class="comment-809278 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809278 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809278"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809018" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ducati" style="position: relative;"> <img src='https://userpic.codeforces.org/699102/avatar/eff3c352646e914e.jpg'/> </a> <div><a href="/profile/ducati" title="Grandmaster ducati" class="rated-user user-red">ducati</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 03:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809018" href="?#comment-809018" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809018" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="699102" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809018"> <div class="moveup"> <div class="ttypography"><p>Although Div.2 D is harder than ever, in my opinion, it's such a useful and excellent problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-809018 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809018 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809018"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809046" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KanishkGoel" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/KanishkGoel" title="Expert KanishkGoel" class="rated-user user-blue">KanishkGoel</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809046" href="?#comment-809046" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809046" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1917239" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809046"> <div class="moveup"> <div class="ttypography"><p>Is it usual for people to post solutions online during the contest like this channel? <a href="https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ">https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809046 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809046 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809046"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809051" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809051" href="?#comment-809051" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809051"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain why this submission <a href="/contest/1541/submission/120562335" title="Посылка 120562335 от Karnania7201">120562335</a> is failing for Div2 B? It would be a great help.</p></div> </div> </div> <div class="reply info"> <a class="comment-809051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809051"> <li> <div class="comment"> <table class="comment-table" commentId="809076" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809076" href="?#comment-809076" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809076" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809076"> <div class="moveup"> <div class="ttypography"><p>Bro you did not included the condition that i and j should be different i.e (i != j) because it is given in question that no are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-809076 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809076 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809076"> <li> <div class="comment"> <table class="comment-table" commentId="809079" commentParentId="809076"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:08">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809079" href="?#comment-809079" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809076" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809079" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809079"> <div class="moveup"> <div class="ttypography"><p>I think its covered as I started j from i+1. I tried that explicitly too but it didn't work. I wrote the same idea in a different way and it worked but this kind of implementation is not working.</p></div> </div> </div> <div class="reply info"> <a class="comment-809079 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809079 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809079"> <li> <div class="comment"> <table class="comment-table" commentId="809082" commentParentId="809079"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809082" href="?#comment-809082" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809079" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809082" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809082"> <div class="moveup"> <div class="ttypography"><p>yeah, you are right, I run your code using vector instead of creating memeset it worked fine, i guess there is some problem in that. <a href="https://codeforces.com/contest/1541/submission/120633207">120633207</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809082 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809082 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809082"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809081" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_NICkk" style="position: relative;"> <img src='https://userpic.codeforces.org/1543175/avatar/6084dd87f2c1cad9.jpg'/> </a> <div><a href="/profile/_NICkk" title="Expert _NICkk" class="rated-user user-blue">_NICkk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809081" href="?#comment-809081" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809081" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1543175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809081"> <div class="moveup"> <div class="ttypography"><p>Only fault in your code is that you didn't used memset correctly </p><p>I just changed your memset with this &quot; memset(ind, 0, sizeof(ind)) &quot; and it worked perfectly fine</p></div> </div> </div> <div class="reply info"> <a class="comment-809081 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809081 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809081"> <li> <div class="comment"> <table class="comment-table" commentId="809091" commentParentId="809081"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:37">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809091" href="?#comment-809091" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809081" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809091" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809091"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot to both of you. I shouldn't have used it without properly knowing about it. </p></div> </div> </div> <div class="reply info"> <a class="comment-809091 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809091 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809091"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809064" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vrintle" style="position: relative;"> <img src='https://userpic.codeforces.org/1991777/avatar/24d9007095afbbb6.jpg'/> </a> <div><a href="/profile/vrintle" title="Master vrintle" class="rated-user user-orange">vrintle</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809064" href="?#comment-809064" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809064" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1991777" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809064"> <div class="moveup"> <div class="ttypography"><p>Instead of $$$a_i \cdot a_j \leq 2n$$$, we could also check $$$a_i \cdot a_j \leq i+n$$$ which is a bit faster ($$$ \sim 62ms$$$).</p></div> </div> </div> <div class="reply info"> <a class="comment-809064 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809064 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809064"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809066" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809066" href="?#comment-809066" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809066" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809066"> <div class="moveup"> <div class="ttypography"><p>can anyone explain B. pleasant pairs more easy words?? </p></div> </div> </div> <div class="reply info"> <a class="comment-809066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809066"> <li> <div class="comment"> <table class="comment-table" commentId="809067" commentParentId="809066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809067" href="?#comment-809067" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809067" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809067"> <div class="moveup"> <div class="ttypography"><p>And also what is ask in 3rd question i cant understand what asked in it</p></div> </div> </div> <div class="reply info"> <a class="comment-809067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809067"> <li> <div class="comment"> <table class="comment-table" commentId="809070" commentParentId="809067"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809070" href="?#comment-809070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809067" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809070"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">https://www.youtube.com/watch?v=xCj_ZR5kENo</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809098" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809098" href="?#comment-809098" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809098" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809098"> <div class="moveup"> <div class="ttypography"><p>For those who are searching for a simple solution for great Graphs problems in O (nlogn). <a href="https://codeforces.com/contest/1541/submission/120600816">https://codeforces.com/contest/1541/submission/120600816</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809098 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809098 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809098"> <li> <div class="comment"> <table class="comment-table" commentId="809119" commentParentId="809098"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fjvzr" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/fjvzr" title="Newbie fjvzr" class="rated-user user-gray">fjvzr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809119" href="?#comment-809119" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809098" style="font-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="809119" 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="809119" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1623986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809119"> <div class="moveup"> <div class="ttypography"><p>Bro can u explain this soln????? i thought of taking all pairs that give negative edges except for the adjacent pairs.... bt getting wrong ans in 3rd 4th test case.....</p><p>while(n&gt;2) { sum-=(n-2)*(llabs(a[j]-a[i])); n--; // n = size i++; // i = 0 j--; // j = n-1 } cout&lt;&lt;sum&lt;&lt;endl;</p><p><a href="https://codeforces.com/contest/1541/submission/120636509">mysoln</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809119 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809119 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809119"> <li> <div class="comment"> <table class="comment-table" commentId="809124" commentParentId="809119"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809124" href="?#comment-809124" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809119" style="font-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="809124" 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="809124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809124"> <div class="moveup"> <div class="ttypography"><p>My solution is simple. First sort the array. </p><p>Then start connecting adjacent values with their differences. This way sum of all edges with positive weight will be same as the sum of adjacent differences in the array.</p><p>After that start making negative edges for every i. So each i will have i negative edges. Where negative weight is same as -(arr[i] — arr[j]).</p><p>Instead of search it for every j I have formula as (prefixsum till i) — arr[i]*i</p></div> </div> </div> <div class="reply info"> <a class="comment-809124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809124"> <li> <div class="comment"> <table class="comment-table" commentId="809132" commentParentId="809124"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809132" href="?#comment-809132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809124" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809132"> <div class="moveup"> <div class="ttypography"><p>can you tell me why are we sorting the array for a particular node call it x we need to add a negative weight from x to 1 , x to 2 x to 3 till x to x-1 keeping in mind the the path sum doesn't become negative so why are we sorting the array</p></div> </div> </div> <div class="reply info"> <a class="comment-809132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809132"> <li> <div class="comment"> <table class="comment-table" commentId="809135" commentParentId="809132"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809135" href="?#comment-809135" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809135" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809135"> <div class="moveup"> <div class="ttypography"><p>We are sorting values only once so as to connect neighboring nodes with minimum values,i.e. difference b/w consecutive values.<br /> From this sum of positive edges will be minimum.</p></div> </div> </div> <div class="reply info"> <a class="comment-809135 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809135 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809135"> <li> <div class="comment"> <table class="comment-table" commentId="809139" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809139" href="?#comment-809139" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809139" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809139"> <div class="moveup"> <div class="ttypography"><p>ohhh thanks I got it</p></div> </div> </div> <div class="reply info"> <a class="comment-809139 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809139 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809139"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809145" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809145" href="?#comment-809145" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809145" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809145"> <div class="moveup"> <div class="ttypography"><p>My solution is working now I only needed to sort the array my code would have been accepted during the contest :(</p></div> </div> </div> <div class="reply info"> <a class="comment-809145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809145"> </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="809116" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ken_KaNeKi_997" style="position: relative;"> <img src='https://userpic.codeforces.org/1737228/avatar/50ceb845253df5d4.jpg'/> </a> <div><a href="/profile/Ken_KaNeKi_997" title="Newbie Ken_KaNeKi_997" class="rated-user user-gray">Ken_KaNeKi_997</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809116" href="?#comment-809116" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809116" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1737228" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809116"> <div class="moveup"> <div class="ttypography"><p>can anyone explain div2 B plz</p></div> </div> </div> <div class="reply info"> <a class="comment-809116 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809116 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809116"> <li> <div class="comment"> <table class="comment-table" commentId="809204" commentParentId="809116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809204" href="?#comment-809204" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809116" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809204" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809204"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/92199#comment-809178">here</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809204 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809204 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809204"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809122" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809122" href="?#comment-809122" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809122" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809122"> <div class="moveup"> <div class="ttypography"><p>Beautiful Problems. Amazing Round!!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-809122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809122"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809156" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dummybawa" style="position: relative;"> <img src='https://userpic.codeforces.org/1704408/avatar/1522f670cd21321.jpg'/> </a> <div><a href="/profile/dummybawa" title="Expert dummybawa" class="rated-user user-blue">dummybawa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809156" href="?#comment-809156" style="font-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="809156" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809156" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1704408" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809156"> <div class="moveup"> <div class="ttypography"><p>UPD: It's wrong. </p></div> </div> </div> <div class="reply info"> <a class="comment-809156 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809156 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809156"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809178" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809178" href="?#comment-809178" style="font-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="809178" 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="809178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809178"> <div class="moveup"> <div class="ttypography"><p>For DIV 2C/1A can anyone explain with this test case N = 6 and D = 0 1 2 3 2 3. What are the edges that we can have with their weights?</p></div> </div> </div> <div class="reply info"> <a class="comment-809178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809178"> <li> <div class="comment"> <table class="comment-table" commentId="809198" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Zemrith" style="position: relative;"> <img src='https://userpic.codeforces.org/1159882/avatar/2a6566e372882267.jpg'/> </a> <div><a href="/profile/Zemrith" title="Expert Zemrith" class="rated-user user-blue">Zemrith</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809198" href="?#comment-809198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-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="809198" 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="809198" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159882" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809198"> <div class="moveup"> <div class="ttypography"><p>Hello! The answer would be -18.</p><p>Diagram: <img alt=" " src="/predownloaded/8c/88/8c88a0230dea9f499896ee59def659611c605976.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Notice that once you sort the distances, the adjacent nodes have no effect on your final answer. But you can add negative edges as long as they are not adjacent, resulting in such a diagram. Hence you can use prefix sums to solve the problem. (if x nodes came before this, for each node, the answer to add is (x-1)*curr value — csum of first (x-1) nodes). </p><p>Hope that made sense!</p></div> </div> </div> <div class="reply info"> <a class="comment-809198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809198"> <li> <div class="comment"> <table class="comment-table" commentId="809218" commentParentId="809198"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:27">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809218" href="?#comment-809218" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809218" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809218"> <div class="moveup"> <div class="ttypography"><p>Thank you <a class="rated-user user-cyan" href="/profile/Zemrith" title="Специалист Zemrith">Zemrith</a> for so much detail explanation and the solution too it helped me a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-809218 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809218 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809218"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809199" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809199" href="?#comment-809199" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809199" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809199"> <div class="moveup"> <div class="ttypography"><p>first sort the array they will from non negative weight edges. 0 -&gt; 1 -&gt; 2 -&gt; 2 -&gt; 3 -&gt; 3 so the non negative weights will be 1 | 1 | 0 | 1 | 0. form here greedily build most negative weights(backward edges) such that there are no negative cycles.</p></div> </div> </div> <div class="reply info"> <a class="comment-809199 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809199 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809199"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809203" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809203" href="?#comment-809203" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809203" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809203"> <div class="moveup"> <div class="ttypography"><p>First you can sort D and get: <code> N = 6, D = [0, 1, 2, 2, 3, 3] </code></p><p>Now calculate the diffs:</p><p><code>diffs = [1, 1, 0, 1, 0]</code></p><p>The edges for this graph could be something like this:</p> <pre><code> 1 1 0 1 0 &lt;- forward edges 1 &lt;-&gt; 2 &lt;-&gt; 3 &lt;-&gt; 4 &lt;-&gt; 5 &lt;-&gt; 6 -1 -1 0 -1 0 &lt;- backward edges </code></pre><p>Now you have to add more negatives edges, and you could do this by choosing some <code>i</code> and <code>j</code>, <code>i &lt; j</code> and add an edges from <code>j</code> to <code>i</code>, and the weight will be sum of the values from <code>diff[i]</code> to <code>diff[j]</code>.</p><p>Another way to think about this is: look at <code>D</code> array, it represents distances between adjacent nodes, all we have to do is add all of the edges with length 2, then all of the edges of length 3, ..., all of the edges of length <code>N - 1</code>.</p><p>So, for our case we would have these edges</p> <pre><code>a b W ------- 1 2 - 1 2 3 - 1 3 4 - 0 &lt;- adjacent forward edges 4 5 - 1 5 6 - 0 2 1 - -1 3 2 - -1 4 3 - 0 &lt;- adjacent backward edges 5 4 - -1 6 5 - 0 3 1 - -2 4 2 - -1 5 3 - -1 &lt;- edges of length 2 6 4 - -1 4 1 - -2 5 2 - -2 &lt;- edges of length 3 6 3 - -1 5 1 - -3 6 2 - -2 &lt;- edges of length 4 6 1 - -3 &lt;- edges of length 5 </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809203 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809203 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809203"> <li> <div class="comment"> <table class="comment-table" commentId="809221" commentParentId="809203"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809221" href="?#comment-809221" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809203" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809221" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809221"> <div class="moveup"> <div class="ttypography"><p>Thank You <a class="rated-user user-green" href="/profile/ilidar" title="Ученик ilidar">ilidar</a> for clearing my doubt and for detailed explaination.</p></div> </div> </div> <div class="reply info"> <a class="comment-809221 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809221 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809221"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809280" href="?#comment-809280" style="font-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="809280" revisionCount="7" revision="7"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">7</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809280" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+18</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809280"> <div class="moveup"> <div class="ttypography"><p>Could someone please provide a more strict intuition or insight of Div2D/Div1B of why &quot;the actual probability p does not matter&quot;? The intuition in the editorial is still alien to me of why those choices of not progess toward to either stacks (and probability 'p' also changes from time to time too) doesn't matter.</p><p>Update: Here is the intuition I came up with (The strict proof can be found in the comment of the author below)</p><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left) in some states of the current tree.</p><p>now, we will try break this $$$dp_{i,j}$$$ down into the sum of $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$</p><p>We will try to illustrate this with trying to split and color, either red or blue, a stick of length $$$1$$$. The length of the sticks representing the 'probability', and the color of the sticks will represent $$$dp_{i-1,j}$$$(red) or $$$dp_{i,j-1}$$$(blue), depending on the color.</p><p>Suppose in the current state, we have probability $$$p$$$ for choosing to pop each stacks, and the rest $$$1-2p$$$ of doing nothing. The picture will look like this:</p><p><a href="https://ibb.co/q9HjQTm"><img alt="Tree-Array-Rep" border="0" src="/predownloaded/13/57/135732d2b0967af0f76c1dba28df72086f234c7d.png" style="max-width: 100.0%;max-height: 100.0%;" /></a></p><p>We will split the stick equally(*) into several sticks of length $$$p$$$, and then color two of them red and blue. (* We can split it evenly because in the original problem, $$$p$$$ is in the form $$$\frac{1}{number\ of\ candidate\ unmark\ nodes}$$$ ) Now, the remaining sticks represent the state of $$$dp_{i,j}$$$ again (in some other state of the entire tree, so might be in some different $$$p$$$). That means we will split those sticks similary.</p><p>The key observations is:</p><p>1) We know that, in the original problem, if we keep picking nodes that aren't progressing toward the target nodes, we will run out of nodes eventually and finally choose the two nodes. That means, all the sticks will eventually colored into 'red' and 'blue'.</p><p>2) When we split a stick into several smaller equal length sticks, we will color two of them into red and blue. <strong>Those two sticks always have the same length</strong>. That means, the total length of blue sticks and the total length of red sticks will be equal in the end.</p><p>Analogically, that means, eventually, $$$dp_{i,j}$$$ will split into $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$ evenly, no matter $$$p$$$ might be or the state of tree of $$$dp_{i,j}$$$ might be. Therefore, $$$dp_{i,j} = \frac{1}{2} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-809280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809280"> <li> <div class="comment"> <table class="comment-table" commentId="809284" commentParentId="809280"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809284" href="?#comment-809284" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809280" style="font-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="809284" 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="809284" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809284"> <div class="moveup"> <div class="ttypography"><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left), with having arbitary probability $$$0 &lt; p \leq 0.5$$$ of chosing to pick the top of each stack (and $$$1-2p$$$ for doing nothing). Then</p><p>$$$dp_{i,j}=\int_{0}^{0.5} x \cdot (dp_{i-1,j}+dp_{i,j-1}) + (1-2x) \cdot dp_{i,j} \,dx$$$</p><p>Solving the equation, we get $$$dp_{i,j}=\frac{1}{6} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$ What is the mistake in this logic?</p></div> </div> </div> <div class="reply info"> <a class="comment-809284 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809284 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809284"> <li> <div class="comment"> <table class="comment-table" commentId="809399" commentParentId="809284"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809399" href="?#comment-809399" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809284" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809399" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809399"> <div class="moveup"> <div class="ttypography"><p>The biggest issue with this logic is that it's assuming $$$p$$$ is arbitrary chosen from a certain state. While $$$p$$$ can be anything in the world, it is always an exact number from a certain state, hence why an integral is wrong. </p><p>As a different type of intuition, you can think, &quot;is it more likely to reach $$$(i-1, j)$$$ than state $$$(i, j-1)$$$&quot;? and vice versa. For me at least, I don't see how it's possible for either of those questions to be true, so they should be equal.</p><p>If you're looking for a more rigorously correct $$$dp$$$, it would look something like this.</p> <div class="spoiler"><b class="spoiler-title">Proof</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp_{i, j, S}$$$ denote the probability of reaching some node $$$i$$$ distance away before some node $$$j$$$ distance away where $$$S$$$ is a representation of the entire state of of the process (not necessarily an integer). I think you already understood why we can assume the $$$lca$$$ is already reached. We aim to show that $$$S$$$ does not matter in our calculation. Assume inductively that $$$S$$$ does not matter. So, we can assume that states $$$(i-1, j)$$$ and states $$$(i, j-1)$$$ are irrelevant to $$$S$$$. Hence, the part we need to care about is $$$(1-2p) dp_{i, j, S \rightarrow S_a}$$$. A way of thinking about this part of the transition is moving through the collection of $$$S$$$ with the state $$$(i, j)$$$. Obviously, the $$$dp$$$ is a $$$DAG$$$ because no state $$$S$$$ can reach another. Each bounce takes a certain probability $$$p$$$ which is just multiplied in the current path. So, for each state $$$S$$$ with state $$$(i, j)$$$, we have a certain probability to reach it by simply calculating $$$dp$$$ along a DAG as is traditional. Then, from those states of $$$(i, j)$$$ you transition to $$$(i, j-1)$$$ with an equal probability $$$(i-1, j)$$$. So, they have to be equal. Finally, this argument holds for any initial state $$$S$$$ that you reach, so we can conclude that, from any state $$$S$$$ with a state of $$$(i, j)$$$, the probability of transitions to $$$(i-1, j)$$$ and $$$(i, j-1)$$$ are always exactly $$$0.5$$$.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-809399 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809399 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809399"> <li> <div class="comment"> <table class="comment-table" commentId="809701" commentParentId="809399"> <tr> <td class="left"> <div style="position: absolute; left: 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/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809701" href="?#comment-809701" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809399" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809701" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809701"> <div class="moveup"> <div class="ttypography"><p>I see, thank you so much!</p></div> </div> </div> <div class="reply info"> <a class="comment-809701 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809701 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809701"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809298" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/satyam_singh93" style="position: relative;"> <img src='https://userpic.codeforces.org/1763011/avatar/9d9fa405de19ab0e.jpg'/> </a> <div><a href="/profile/satyam_singh93" title="Newbie satyam_singh93" class="rated-user user-gray">satyam_singh93</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809298" href="?#comment-809298" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809298" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1763011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809298"> <div class="moveup"> <div class="ttypography"><p>I am getting wrong ans . could someone tell me where the code make differene ( [yestrday competiton problem .</p><p>`](<a href="https://codeforces.com/contest/1541/problem/B)">https://codeforces.com/contest/1541/problem/B)</a>.</p> <pre><code>int main( ) { clock_t begin = clock(); file_i_o(); // Write your code here.... int t; cin&gt;&gt;t; while(t-- ){ int n; cin&gt;&gt;n; vector&lt;pair&lt;int,int&gt;&gt;v; v.push_back({0,0}); loop(i,0,n) { int x; cin&gt;&gt;x; v.pb({x,i+1}); } sort(v.begin()+1,v.end()); int count =0; for(int i=1 ; i&lt;=n;i++) { for(ll j=i+1;j&lt;=n;j++) { ll left = v[i].first * v[j].first; ll right = v[i].second + v[j].second; if(left == right) count++; if(left &gt; 2*n ) break; } } cout&lt;&lt;count&lt;&lt;endl; } </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809298 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809298 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809298"> <li> <div class="comment"> <table class="comment-table" commentId="809305" commentParentId="809298"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809305" href="?#comment-809305" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809298" style="font-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="809305" 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="809305" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809305"> <div class="moveup"> <div class="ttypography"><p>v[i].first * v[j].first can create overflow. So, you need to convert them to long long by using</p><p>ll left = 1LL * v[i].first * v[j].first;</p><p>instead and it would pass.</p><p>(Simply save the value in long long won't help. You need to convert them to long long before doing multiplication. 1LL* is one way)</p></div> </div> </div> <div class="reply info"> <a class="comment-809305 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809305 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809305"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809309" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809309" href="?#comment-809309" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809309" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809309"> <div class="moveup"> <div class="ttypography"><p>Hi, in problem Div1.B/Div2.D; I can't wrap my head around $$$F[x][y]=F[x−1][y]/2+F[x][y−1]/2$$$. Why is it not $$$F[x][y]=F[x−1][y+1]/2+F[x+1][y−1]/2$$$, can someone please explain to me why is my transition wrong and/or why is the aforementioned transition correct? </p></div> </div> </div> <div class="reply info"> <a class="comment-809309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809309"> <li> <div class="comment"> <table class="comment-table" commentId="809311" commentParentId="809309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809311" href="?#comment-809311" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809311" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809311"> <div class="moveup"> <div class="ttypography"><p>x and y is the distance left for each side right? So, if you take one out, it won't make sense to add that one to the other side since the distance should be either x-1 and y or x and y-1.</p></div> </div> </div> <div class="reply info"> <a class="comment-809311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809311"> <li> <div class="comment"> <table class="comment-table" commentId="809339" commentParentId="809311"> <tr> <td class="left"> <div style="position: absolute; left: 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/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809339" href="?#comment-809339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809339" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809339"> <div class="moveup"> <div class="ttypography"><p>Thank you so much I understand. I had a minor misunderstanding of the parameters to the dp state.</p></div> </div> </div> <div class="reply info"> <a class="comment-809339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809339"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809371" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:13">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809371" href="?#comment-809371" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809371" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809371"> <div class="moveup"> <div class="ttypography"><p>PLease explain why 2 same codes are not giving the same ans</p><p>code forces round 728 div2<br />Problem B :<a href="https://codeforces.com/contest/1541/problem/B">https://codeforces.com/contest/1541/problem/B</a></p><p>AC Submission : <a href="https://ide.codingblocks.com/s/579769">https://ide.codingblocks.com/s/579769</a></p><p>Wrong output Submission :<a href="https://ide.codingblocks.com/s/579771">https://ide.codingblocks.com/s/579771</a></p><p>Difference is using of macro (node) instead of pair&lt;int,int&gt; </p><p>Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-809371 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809371 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809371"> <li> <div class="comment"> <table class="comment-table" commentId="809379" commentParentId="809371"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809379" href="?#comment-809379" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809371" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809379" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809379"> <div class="moveup"> <div class="ttypography"><p>If i am using #define node pair&lt;int,int&gt; it is getting accepted but when i am using typedef pair&lt;int,int&gt; node; it is giving wrong answer</p><p>Why this is happening ?? Is it a bug??</p></div> </div> </div> <div class="reply info"> <a class="comment-809379 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809379 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809379"> <li> <div class="comment"> <table class="comment-table" commentId="809407" commentParentId="809379"> <tr> <td class="left"> <div style="position: absolute; left: 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/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 19:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809407" href="?#comment-809407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809379" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809407" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809407"> <div class="moveup"> <div class="ttypography"><p>Not really sure why this is happening.</p><p>However, I think the problem is the position of #define int long long. So, for #define pair&lt;int,int&gt; node it seems that compiler change node -&gt; pair&lt;int,int&gt; -&gt; pair&lt;long long, long long&gt;. However, when you do typedef, it still keeps in pair&lt;int, int&gt; which creates an overflow problem later on. </p><p>I did try moving #define int long long up above typedef and the code pass. So, my best guess is #define int long long only replace int after that position with long long. Thus, node is still pair&lt;int, int&gt; in the typedef solution, while node is changed to pair&lt;long long, long long&gt; in the second solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-809407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809407"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809627" href="?#comment-809627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809627"> <div class="moveup"> <div class="ttypography"><p>May I ask why in the Div1D solution ci=i-bi, I think it should be ci=bi ...</p></div> </div> </div> <div class="reply info"> <a class="comment-809627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809627"> <li> <div class="comment"> <table class="comment-table" commentId="809631" commentParentId="809627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809631" href="?#comment-809631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809631" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809631"> <div class="moveup"> <div class="ttypography"><p>Check the definition of bi again dude. bi here means <strong>number of elements greater than pi</strong>. So to get ci, which is <strong>number of elements smaller than pi</strong>, you need i-bi.</p></div> </div> </div> <div class="reply info"> <a class="comment-809631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809631"> <li> <div class="comment"> <table class="comment-table" commentId="809636" commentParentId="809631"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809636" href="?#comment-809636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809636"> <div class="moveup"> <div class="ttypography"><p>I read it again. If I read it correctly, bi stands for j&lt;i,pj&gt;pi, and ci stands for j&gt;i,pj&lt;pi. For example, p={1,3,5,4,6,2}, I think b4=1,c4=1, please point out my problem</p></div> </div> </div> <div class="reply info"> <a class="comment-809636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809636"> <li> <div class="comment"> <table class="comment-table" commentId="809638" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809638" href="?#comment-809638" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809638" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809638"> <div class="moveup"> <div class="ttypography"><p>oh, the array index starts from 1</p></div> </div> </div> <div class="reply info"> <a class="comment-809638 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809638 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809638"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809639" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809639" href="?#comment-809639" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809639" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809639"> <div class="moveup"> <div class="ttypography"><p>You are right.</p><p>I guess it might just be typo and ci stands for j&lt;i, pj&lt;pi. At least with this definition of ci the algorithm seems correct :)</p></div> </div> </div> <div class="reply info"> <a class="comment-809639 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809639 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809639"> <li> <div class="comment"> <table class="comment-table" commentId="809641" commentParentId="809639"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809641" href="?#comment-809641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809639" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809641"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-809641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809641"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809705" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/darthrevenge" style="position: relative;"> <img src='https://userpic.codeforces.org/1567000/avatar/ee31d2a91a9575b9.jpg'/> </a> <div><a href="/profile/darthrevenge" title="Candidate Master darthrevenge" class="rated-user user-violet">darthrevenge</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809705" href="?#comment-809705" style="font-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="809705" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809705" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1567000" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809705"> <div class="moveup"> <div class="ttypography"><p>Here's my solution of B div 1 / D div 2 without LCA, using single DFS per node. <a href="/contest/1540/submission/120700765" title="Посылка 120700765 от darthrevenge">120700765</a> It is similar to what <a class="rated-user user-violet" href="/profile/OleschY" title="Кандидат в мастера OleschY">OleschY</a> suggested above. I've tried to describe it in the <a href="https://codeforces.com/blog/entry/92284">blog</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-809705 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809705 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809705"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809951" href="?#comment-809951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809951"> <div class="moveup"> <div class="ttypography"><p>Can someone explain how you can find the LCA for each pair so quick? Iterating through every root is and then considering every pair is already N^3</p></div> </div> </div> <div class="reply info"> <a class="comment-809951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809951"> <li> <div class="comment"> <table class="comment-table" commentId="809965" commentParentId="809951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PurpleCrayon" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809965" href="?#comment-809965" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809965" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="1604355" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809965"> <div class="moveup"> <div class="ttypography"><p>There are a couple ways you could do it:</p> <ol> <li>Just use standard binary lifting (initialize once for each root). This runs in $$$\mathcal{O}(n^3 \log{}n)$$$, and should pass under the given constraints. You could also just use $$$\mathcal{O}(1)$$$ lca using an rmq over an euler tour.</li> <li>You could use a version of dp, where $$$dp[a][b] = lca(a, b)$$$. If the depth of $$$a$$$ is greater than the depth of $$$b$$$, $$$dp[a][b] = dp[parent[a]][b]$$$, otherwise $$$dp[a][b] = dp[a][parent[b]]$$$. The base cases are $$$dp[a][a] = a$$$ for all $$$a$$$. This runs in $$$\mathcal{O}(n^3)$$$.</li> <li>You could extend this idea and do the main solution's dp directly on the tree (without ever worrying about lca's). The recurrence is equivalent to the main solution ($$$dp[a][b] = \frac{dp[parent[a]][b]+dp[a][parent[b]]}{2}$$$ with the base cases being one node is an ancestor of the other.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-809965 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809965 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809965"> <li> <div class="comment"> <table class="comment-table" commentId="809967" commentParentId="809965"> <tr> <td class="left"> <div style="position: absolute; left: 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/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809967" href="?#comment-809967" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809965" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809967" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809967"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the detailed answer!</p></div> </div> </div> <div class="reply info"> <a class="comment-809967 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809967 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809967"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="810320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Anurag_20" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Anurag_20" title="Specialist Anurag_20" class="rated-user user-cyan">Anurag_20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/30/2021 19:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810320" href="?#comment-810320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810320" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1600346" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810320"> <div class="moveup"> <div class="ttypography"><p>O(n2) is also working for div2 C Great Graphs. <a href="https://codeforces.com/contest/1540/submission/120964787">https://codeforces.com/contest/1540/submission/120964787</a></p></div> </div> </div> <div class="reply info"> <a class="comment-810320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810320"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="813828" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/T404" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/T404" title="Master T404" class="rated-user user-orange">T404</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/09/2021 19:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-813828" href="?#comment-813828" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="813828" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="523287" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-813828"> <div class="moveup"> <div class="ttypography"><p>Div1D can be done in $$$O(n \sqrt{n})$$$. We can use square root decomposition to replace all BITs in tutorial. Since a value in a non-updated position changes by at most one and all values change in the same direction, the full recomputation is only needed in the updated position and we can perform an incremental change in $$$O(1)$$$ for values in each non-updated positions.</p><p><a href="https://codeforces.com/contest/1540/submission/121831547">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-813828 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-813828 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-813828"> <li> <div class="comment"> <table class="comment-table" commentId="834051" commentParentId="813828"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KeyID" style="position: relative;"> <img src='https://userpic.codeforces.org/226684/avatar/10e3671716bf6859.jpg'/> </a> <div><a href="/profile/KeyID" title="Grandmaster KeyID" class="rated-user user-red">KeyID</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/29/2021 12:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-834051" href="?#comment-834051" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-813828" style="font-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="834051" 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="834051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="226684" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-834051"> <div class="moveup"> <div class="ttypography"><p>Realy impressive solution. I'm surprised no stars were given to you until me. Maybe many people didn't get your idea since the solution is actually much more complicated than your brief comment(at least in my opinion). I also wrote a piece of code which used your method but simplified a small part of steps. <a href="https://codeforces.com/contest/1540/submission/127317031">Here</a> it is.</p></div> </div> </div> <div class="reply info"> <a class="comment-834051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-834051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-834051"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="837924" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Harolinch" style="position: relative;"> <img src='https://userpic.codeforces.org/427341/avatar/cf8608aeb55edc95.jpg'/> </a> <div><a href="/profile/Harolinch" title="Pupil Harolinch" class="rated-user user-green">Harolinch</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837924" href="?#comment-837924" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837924" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="427341" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837924"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a> in problem Tree array you said that Fixing a given root r, the expected value of the entire process is obviously the sum of the expected values for a fixed root divided by n.</p><p>why we divide by n at the end ? </p></div> </div> </div> <div class="reply info"> <a class="comment-837924 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837924 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837924"> <li> <div class="comment"> <table class="comment-table" commentId="837928" commentParentId="837924"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837928" href="?#comment-837928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-837924" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837928" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837928"> <div class="moveup"> <div class="ttypography"><p>The calculation is independent based on whichever node that you choose first (it becomes the “root”). Initially you choose one of $$$n$$$ nodes with equal probability so you divide by $$$n$$$ at the end after you’ve summed up the independent expected value after choosing the node $$$i$$$ initially.</p></div> </div> </div> <div class="reply info"> <a class="comment-837928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837928"> </ul> </div> </li> </ul> </div> <br/> <div id="editBox-100805" 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 firstPreview100805 = true; var lastPreviewContent100805 = ''; 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=100805] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=100805] 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-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, 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:33:28</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:'81289372dffb0c4e',t:'MTY5NjcwNzIwOC45MzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1541D
1541
D
ru
D. Древесный массив
<div class="problem-statement"><div class="header"><div class="title">D. Древесный массив</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задано дерево, состоящее из $$$n$$$ вершин. По заданному дереву вы строите массив, отмечая вершины по одной.</p><p>Первоначально, когда еще не помечено ни одной вершины, вы выбираете вершину равновероятно по всем вершинам дерева и отмечаете ее.</p><p>После этого, пока еще остаются непомеченные вершины, вы выбираете и помечаете вершину равновероятно среди всех еще непомеченных, но связанных по ребру хотя бы с одной помеченной вершиной.</p><p>Можно доказать, что данный процесс пометит все вершины в дереве.</p><p>Финальный массив $$$a$$$ — это список номеров вершин в порядке, в котором они были помечены.</p><p>Определите математическое ожидание количества инверсий в массиве, полученном на основе заданного дереве с помощью описанного выше алгоритма.</p><p>Количество инверсий в массиве $$$a$$$ — это количество пар индексов $$$(i, j)$$$ таких, что $$$i &lt; j$$$ и $$$a_i &gt; a_j$$$. Например, в массиве $$$[4, 1, 3, 2]$$$ количество инверсий равно $$$4$$$: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$2 \le n \le 200$$$) — количество вершин в дереве.</p><p>В следующих $$$n - 1$$$ строках заданы по два целых числа $$$x$$$ и $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), означающие ребро между вершинами $$$x$$$ и $$$y$$$.</p><p>Гарантируется, что заданные ребра образуют дерево.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите математическое ожидание количества инверсий в построенном массиве по модулю $$$10^9+7$$$.</p><p>Формально, пусть $$$M = 10^9+7$$$. Можно показать, что ответ может быть представлен в виде несократимой дроби $$$\frac{p}{q}$$$, где $$$p$$$ и $$$q$$$ — целые числа, и $$$q \not \equiv 0 \pmod{M}$$$. Выведите целое число, равное $$$p \cdot q^{-1} \bmod M$$$. Другими словами, выведите такое целое число $$$x$$$, что $$$0 \le x &lt; M$$$ и $$$x \cdot q \equiv p \pmod{M}$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 166666669 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 2 1 2 3 6 1 1 4 2 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 500000009 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 2 1 3 1 4 2 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 500000007 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Изображение дерева из первого примера:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/90dc1d034031a6ea1791910813d434e41e5d6432.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>В первом примере получающиеся массивы почти фиксированы. Если первоначально выбрана вершина $$$2$$$, то единственный возможный массив — это $$$[2, 1, 3]$$$ ($$$1$$$ инверсия). Если первоначально выбрана вершина $$$3$$$, то единственный возможный массив — это $$$[3, 1, 2]$$$ ($$$2$$$ инверсии). Если первоначально выбрана вершина $$$1$$$, то массивы $$$[1, 2, 3]$$$ ($$$0$$$ инверсий) и $$$[1, 3, 2]$$$ ($$$1$$$ инверсия) — это единственные варианты и они равновероятны. В результате математическое ожидание количества инверсий равно $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. </p><p>$$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, то есть ответ равен $$$166666669$$$.</p><p>Изображение дерева из второго примера: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/ef4aded5d5aff1ddebfd0e869167f44b63b678ac.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Изображение дерева из третьего примера: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/6ba27b979f5664e506fd0ae1d4c088000cac0fea.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="31ac1f445594730bfa9782989a7e8f36"/> <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="3a2e30eec6604291efb1f3ef212d19e2d7715bd7"/> <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='31ac1f445594730bfa9782989a7e8f36'>&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%2F1541%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='31ac1f445594730bfa9782989a7e8f36'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1541">Codeforces Round 728 (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='31ac1f445594730bfa9782989a7e8f36'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1541/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='31ac1f445594730bfa9782989a7e8f36'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1027095"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='31ac1f445594730bfa9782989a7e8f36'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1027095"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92093" title="Codeforces Round #728" target="_blank">Codeforces Round #728 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13929" resourceName="Codeforces Round #728" resourceManual="true" src="//codeforces.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/92199" title="Tutorial" target="_blank">Tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13941" 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/1541">Задачи</a></li> <li><a href="/contest/1541/submit">Отослать</a></li> <li><a href="/contest/1541/my">Мои посылки</a></li> <li><a href="/contest/1541/status">Статус</a></li> <li><a href="/contest/1541/hacks">Взломы</a></li> <li><a href="/contest/1541/room/1">Комната</a></li> <li><a href="/contest/1541/standings">Положение</a></li> <li><a href="/contest/1541/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8dabbc3a7920597b8cb9ecc1e2223dc1ff969f36"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ вершин. По заданному дереву вы строите массив, отмечая вершины по одной.</p><p>Первоначально, когда еще не помечено ни одной вершины, вы выбираете вершину равновероятно по всем вершинам дерева и отмечаете ее.</p><p>После этого, пока еще остаются непомеченные вершины, вы выбираете и помечаете вершину равновероятно среди всех еще непомеченных, но связанных по ребру хотя бы с одной помеченной вершиной.</p><p>Можно доказать, что данный процесс пометит все вершины в дереве.</p><p>Финальный массив $$$a$$$ — это список номеров вершин в порядке, в котором они были помечены.</p><p>Определите математическое ожидание количества инверсий в массиве, полученном на основе заданного дереве с помощью описанного выше алгоритма.</p><p>Количество инверсий в массиве $$$a$$$ — это количество пар индексов $$$(i, j)$$$ таких, что $$$i &lt; j$$$ и $$$a_i &gt; a_j$$$. Например, в массиве $$$[4, 1, 3, 2]$$$ количество инверсий равно $$$4$$$: $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(1, 4)$$$, $$$(3, 4)$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$2 \le n \le 200$$$) — количество вершин в дереве.</p><p>В следующих $$$n - 1$$$ строках заданы по два целых числа $$$x$$$ и $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \neq y$$$), означающие ребро между вершинами $$$x$$$ и $$$y$$$.</p><p>Гарантируется, что заданные ребра образуют дерево.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите математическое ожидание количества инверсий в построенном массиве по модулю $$$10^9+7$$$.</p><p>Формально, пусть $$$M = 10^9+7$$$. Можно показать, что ответ может быть представлен в виде несократимой дроби $$$\frac{p}{q}$$$, где $$$p$$$ и $$$q$$$ — целые числа, и $$$q \not \equiv 0 \pmod{M}$$$. Выведите целое число, равное $$$p \cdot q^{-1} \bmod M$$$. Другими словами, выведите такое целое число $$$x$$$, что $$$0 \le x &lt; M$$$ и $$$x \cdot q \equiv p \pmod{M}$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 166666669 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 2 1 2 3 6 1 1 4 2 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 500000009 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 2 1 3 1 4 2 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 500000007 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Изображение дерева из первого примера:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/90dc1d034031a6ea1791910813d434e41e5d6432.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>В первом примере получающиеся массивы почти фиксированы. Если первоначально выбрана вершина $$$2$$$, то единственный возможный массив — это $$$[2, 1, 3]$$$ ($$$1$$$ инверсия). Если первоначально выбрана вершина $$$3$$$, то единственный возможный массив — это $$$[3, 1, 2]$$$ ($$$2$$$ инверсии). Если первоначально выбрана вершина $$$1$$$, то массивы $$$[1, 2, 3]$$$ ($$$0$$$ инверсий) и $$$[1, 3, 2]$$$ ($$$1$$$ инверсия) — это единственные варианты и они равновероятны. В результате математическое ожидание количества инверсий равно $$$\frac{1}{3}\cdot 1 + \frac{1}{3} \cdot 2 + \frac{1}{3} \cdot (\frac{1}{2} \cdot 0 + \frac{1}{2} \cdot 1) = \frac{7}{6}$$$. </p><p>$$$166666669 \cdot 6 = 7 \pmod {10^9 + 7}$$$, то есть ответ равен $$$166666669$$$.</p><p>Изображение дерева из второго примера: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/ef4aded5d5aff1ddebfd0e869167f44b63b678ac.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Изображение дерева из третьего примера: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/6ba27b979f5664e506fd0ae1d4c088000cac0fea.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c70baf5c005d',t:'MTY5NjY2NzM3OC42MDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0412\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0438, \u043c\u0430\u0442. \u043e\u0436\u0438\u0434\u0430\u043d\u0438\u044f, \u0441\u043b\u0443\u0447\u0430\u0439\u043d\u044b\u0435 \u0432\u0435\u043b\u0438\u0447\u0438\u043d\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*2300"]
https://codeforces.com/blog/entry/92199
<!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="ea33d124a1ff874ace73f937748d303e"/> <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="Codeforces Round #728 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #728 Editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='ea33d124a1ff874ace73f937748d303e'>&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%2F92199">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='ea33d124a1ff874ace73f937748d303e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:31:32</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:31:32</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='ea33d124a1ff874ace73f937748d303e'/> <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/PurpleCrayon">PurpleCrayon</a></li> <li class="current selectedLava"><a href="/blog/PurpleCrayon">Blog</a></li> <li><a href="/teams/with/PurpleCrayon">Teams</a></li> <li><a href="/submissions/PurpleCrayon">Submissions</a></li> <li><a href="/groups/with/PurpleCrayon">Groups</a></li> <li><a href="/contests/with/PurpleCrayon">Contests</a></li> <li><a href="/contests/writer/PurpleCrayon">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/PurpleCrayon" style="text-decoration:none;color:black !important;">PurpleCrayon's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="92809"> <div class="title"> <a href="/blog/entry/92199"> <p>Codeforces Round #728 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a>, <a href="/topic/92809/en10">history</a>, <span class="format-humantime" title="Jun/25/2021 20:44">2 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><a href="/contest/1541/problem/A" title="Codeforces Round 728 (Div. 2)">1541A - Pretty Permutations</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The parity (whether $$$n$$$ is odd or even) matters.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Swapping two adjacent cats keeps both of them close to their original location and changes both of their locations.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>If $$$n$$$ is even, the optimal distance is $$$n$$$, and if $$$n$$$ is odd the optimal distance is $$$n+1$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541A">Tutorial is loading...</div></div></div><p><a href="/contest/1541/problem/B" title="Codeforces Round 728 (Div. 2)">1541B - Pleasant Pairs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>$$$i+j \leq 2 \cdot n$$$</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The number of pairs $$$(a, b)$$$ such that $$$a \cdot b \leq x$$$ is $$$O(x log x)$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/A" title="Codeforces Round 728 (Div. 1)">1540A - Great Graphs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What's the minimum value that an edge from $$$a$$$ to $$$b$$$ can be?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use edges with negative value whenever you can.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The sum of the values of edges with positive weight must be $$$\geq$$$ the maximum value in the array.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540A">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Tree Array</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Fix the initial node chosen and root the tree there, what is the contribution of each pair of nodes?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Nothing matters besides the path from node $$$a$$$ to node $$$b$$$, and the initially chosen node $$$r$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>You are given two stacks of size $$$a_1$$$ and $$$a_2$$$. In a single step, you randomly choose a stack to remove a single item from. What is the probability that $$$a_1$$$ becomes $$$0$$$ before $$$a_2$$$? Can you extend this argument for an arbitrary probability $$$p$$$ to remove from one of the two stacks, and a probability of $$$1-2p$$$ to do nothing?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/C2" title="Codeforces Round 728 (Div. 1)">1540C2 - Converging Array (Hard Version)</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What are the invariants? The monovariants?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What is the prefix sum array of the converged array? What is the difference array of the converged array?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you conducted the process on a prefix of size $$$1$$$, then of size $$$2$$$, and on and on?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How many values $$$x$$$ are actually interesting?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540C2">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Inverse Inversions</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The answer is always unique.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Try to figure out what the location of the $$$i$$$-th element would be if you only looked at the first $$$i$$$ elements, then the first $$$i+1$$$, etc. to find an $$$O(nq)$$$ solution.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use sqrt decomposition to optimize it.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540D">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/E" title="Codeforces Round 728 (Div. 1)">1540E - Tasty Dishes</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How much does each chef's initial dish contribute at time $$$k$$$?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you really, really wanted to use matrix exponentiation?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How can you multiply some vectors by a matrix in $$$O(N)$$$ time? (go back to linear algebra class)</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Decompose into linear combinations of eigenvectors.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540E">Tutorial is loading...</div></div></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/1540" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 1)</a> </span> </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/1541" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-191295-92809").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "191295", blogEntryId: "92199", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-92809"><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'>+96</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-92809"><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/PurpleCrayon"><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/PurpleCrayon"> PurpleCrayon </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="Jun/25/2021 20:44">2 years ago</span> </li> <li> <a href="/blog/entry/92199#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/92199#comments"> 170 </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="100805"> <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 (136)</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="808750" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808750" href="?#comment-808750" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808750" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-66" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-66</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808750"> <div class="moveup"> <div class="ttypography"><p>PURPLECRAYON ORZ</p></div> </div> </div> <div class="reply info"> <a class="comment-808750 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808750 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808750"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808751" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hbarp" style="position: relative;"> <img src='https://userpic.codeforces.org/1387715/avatar/c727a810db6ffb66.jpg'/> </a> <div><a href="/profile/hbarp" title="Candidate Master hbarp" class="rated-user user-violet">hbarp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808751" href="?#comment-808751" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808751" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="1387715" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-83</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808751"> <div class="moveup"> <div class="ttypography"><p>Damn, so orz round. <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Мастер PurpleCrayon">PurpleCrayon</a> orz</p></div> </div> </div> <div class="reply info"> <a class="comment-808751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808751"> <li> <div class="comment"> <table class="comment-table" commentId="808805" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/naman1601" style="position: relative;"> <img src='https://userpic.codeforces.org/1703219/avatar/d63fc523dc05fda8.jpg'/> </a> <div><a href="/profile/naman1601" title="Master naman1601" class="rated-user user-orange">naman1601</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808805" href="?#comment-808805" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808805" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-51" data-commentUserId="1703219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-51</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808805"> <div class="moveup"> <div class="ttypography"><p>yeah, amazing problemset, not speedforces at all :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808805 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808805 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808805"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808817" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LOVELY_BOY_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/LOVELY_BOY_" title="Newbie LOVELY_BOY_" class="rated-user user-gray">LOVELY_BOY_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808817" href="?#comment-808817" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-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="808817" 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="808817" class="CommentVoteFrame" data-commentRating="35" data-commentUserId="2089809" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808817"> <div class="moveup"> <div class="ttypography"><p>LOL <a class="rated-user user-blue" href="/profile/hbarp" title="Эксперт hbarp">hbarp</a>,even you didn't participate in the contest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808817 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808817 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808817"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808753" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DontLookBack" style="position: relative;"> <img src='https://userpic.codeforces.org/1534766/avatar/4eacdc5f9758fc28.jpg'/> </a> <div><a href="/profile/DontLookBack" title="Specialist DontLookBack" class="rated-user user-cyan">DontLookBack</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808753" href="?#comment-808753" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808753" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1534766" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808753"> <div class="moveup"> <div class="ttypography"><p>I am curious, how many div2 testers solved D?</p></div> </div> </div> <div class="reply info"> <a class="comment-808753 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808753 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808753"> <li> <div class="comment"> <table class="comment-table" commentId="808826" commentParentId="808753"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/highonjuice" style="position: relative;"> <img src='https://userpic.codeforces.org/1457566/avatar/f7988dd2af03d38b.jpg'/> </a> <div><a href="/profile/highonjuice" title="Pupil highonjuice" class="rated-user user-green">highonjuice</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808826" href="?#comment-808826" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808753" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808826" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1457566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808826"> <div class="moveup"> <div class="ttypography"><p>like 2 ppl, it was hard for me</p></div> </div> </div> <div class="reply info"> <a class="comment-808826 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808826 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808826"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808757" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tlatoani" style="position: relative;"> <img src='https://userpic.codeforces.org/614001/avatar/598b4e8358aad1b4.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/Tlatoani" title="Grandmaster Tlatoani" class="rated-user user-red">Tlatoani</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:18">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808757" href="?#comment-808757" style="font-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="808757" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="808757" class="CommentVoteFrame" data-commentRating="121" data-commentUserId="614001" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+121</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808757"> <div class="moveup"> <div class="ttypography"><h4>Alternate solution to <a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Инвертируем инверсии</a></h4><p>(Read the first nontrivial paragraph of the editorial before reading this alternate solution)</p><p>Let $$$p_r(k) = x$$$ denote that of the numbers $$$p(1), \ldots, p(r)$$$ in sorted order, $$$p(k)$$$ is equal to the $$$x$$$th of these numbers. We will take a decomposition strategy just as the editorial does, though our strategy will be different. We will divide $$$[1, n]$$$ into blocks of length $$$b$$$. For each block covering some interval $$$[l, r]$$$, we will store $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>This means that for any $$$k$$$, if we know $$$p_r(k)$$$ for some block $$$[l, r]$$$, then we can determine $$$p_{r'}(k)$$$ for the block $$$[l', r']$$$ immediately to the right by binary searching on the numbers stored for $$$[l', r']$$$. Therefore, we can perform queries in $$$O\left(\frac n b \lg b\right)$$$.</p><p>We now need to figure out updates. There are probably simple ways to perform updates in $$$O(b\lg b)$$$, but this yields an overall runtime of $$$O(q\sqrt n \lg n)$$$ which is too slow.</p><p>Therefore, we can instead store each block as a segment tree. For each range $$$[l, r]$$$ in the segment tree we store the same thing we store for the whole block: $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>We then have to quickly merge two intervals. We can merge two intervals of length $$$\lambda$$$ in $$$O(\lambda \lg \lambda)$$$ by doing binary search just as we did above, but this still only yields $$$O(b\lg b)$$$ update overall. However, these $$$\lambda$$$ binary searches can be optimized using two pointers to $$$O(\lambda)$$$, making the overall update $$$O(b)$$$.</p><p>We thus have $$$O\left(\frac n b \lg b\right)$$$ query and $$$O(b)$$$ update. Therefore, we can choose $$$b = \sqrt{n\lg n}$$$ to attain an overall runtime of $$$O\left(q\sqrt{n\lg n}\right)$$$ just as the editorial does.</p><p><a href="https://codeforces.com/contest/1540/submission/120611645">Submission in Kotlin</a></p><p><a href="https://codeforces.com/contest/1540/submission/120612729">Submission in C++</a></p><p>It is interesting to note that this solution is quite fast. At the time of writing this update, the C++ version is the fastest correct submission (and runs under 1 second!) and the Kotlin version is faster than the vast majority of submissions.</p></div> </div> </div> <div class="reply info"> <a class="comment-808757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808757"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808765" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardcode229" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardcode229" title="Newbie hardcode229" class="rated-user user-gray">hardcode229</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808765" href="?#comment-808765" style="font-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="808765" 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="808765" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1635180" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808765"> <div class="moveup"> <div class="ttypography"><p>The 3rd hint for the second problem is same as that of the first problem, is it related or a mistake? <strong>UPD:</strong> it is corrected.</p></div> </div> </div> <div class="reply info"> <a class="comment-808765 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808765 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808765"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808769" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/peanut" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/peanut" title="Specialist peanut" class="rated-user user-cyan">peanut</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:24">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808769" href="?#comment-808769" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808769" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="1167233" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+22</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808769"> <div class="moveup"> <div class="ttypography"><p>speedforces.</p></div> </div> </div> <div class="reply info"> <a class="comment-808769 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808769 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808769"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808781" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/graphs_11" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/graphs_11" title="Specialist graphs_11" class="rated-user user-cyan">graphs_11</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808781" href="?#comment-808781" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808781" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1610110" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808781"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">Problem B Detailed Explanation</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808781 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808781 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808781"> <li> <div class="comment"> <table class="comment-table" commentId="809069" commentParentId="808781"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:40">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809069" href="?#comment-809069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808781" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809069" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809069"> <div class="moveup"> <div class="ttypography"><p>Thank you, very well explained</p></div> </div> </div> <div class="reply info"> <a class="comment-809069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809069"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808790" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PC_E1052" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PC_E1052" title="Pupil PC_E1052" class="rated-user user-green">PC_E1052</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808790" href="?#comment-808790" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808790" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="811219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808790"> <div class="moveup"> <div class="ttypography"><p>c was too easy, d was too hard. but d was very nice problem though. </p></div> </div> </div> <div class="reply info"> <a class="comment-808790 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808790 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808790"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808793" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808793" href="?#comment-808793" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808793" class="CommentVoteFrame" data-commentRating="58" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+58</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808793"> <div class="moveup"> <div class="ttypography"><p>Paging <a class="rated-user user-legendary" href="/profile/ecnerwala" title="Легендарный гроссмейстер ecnerwala"><span class="legendary-user-first-letter">e</span>cnerwala</a> to explain his solution to D1E if he'd like. It seems offline?</p></div> </div> </div> <div class="reply info"> <a class="comment-808793 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808793 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808793"> <li> <div class="comment"> <table class="comment-table" commentId="808979" commentParentId="808793"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ecnerwala" 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/ecnerwala" title="Legendary Grandmaster ecnerwala" class="rated-user user-legendary"><span class="legendary-user-first-letter">e</span>cnerwala</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808979" href="?#comment-808979" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808793" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808979" class="CommentVoteFrame" data-commentRating="40" data-commentUserId="57502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808979"> <div class="moveup"> <div class="ttypography"><p>My solution is $$$O(K N^3 + QN)$$$. I just precomputed the coefficient of each $$$a_i$$$ for each prefix-range for each number of days since person $$$i$$$ becomes positive (only $$$1000$$$ possible days) in $$$O(N \cdot K \cdot N^2)$$$, and then summed up the appropriate ones to answer each query in $$$O(N)$$$. It's written in the offline style to use only $$$O(KN)$$$ memory at a time (grouped by $$$a_i$$$) instead of $$$O(KN^2)$$$.</p><p>My passing submission is just $$$KN^3 / 6$$$ instead of the $$$KN^3$$$ I submitted in contest :'(</p><p>If you guys wanted to prevent this, $$$K$$$ could've been much higher, like $$$1e18$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808979 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808979 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808979"> <li> <div class="comment"> <table class="comment-table" commentId="809002" commentParentId="808979"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809002" href="?#comment-809002" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808979" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809002" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809002"> <div class="moveup"> <div class="ttypography"><p>:( I knew of this solution (it’s why ML is tight) but I didn’t realize that it could be done offline with small memory. Of course $$$K$$$ higher is obvious solution but main issue is that the extra modulos from binary exponentiation make it very hard to pass in Java without allowing other unoptimal solutions through such as precomputing inverses of the matrix. Probably $$$k=10^5$$$ would’ve been a better choice. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-809002 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809002 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809002"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808795" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zukonit14" style="position: relative;"> <img src='https://userpic.codeforces.org/1192187/avatar/5afd49be87fb87d9.jpg'/> </a> <div><a href="/profile/zukonit14" title="Expert zukonit14" class="rated-user user-blue">zukonit14</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808795" href="?#comment-808795" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808795" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1192187" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808795"> <div class="moveup"> <div class="ttypography"><p>Does Div2 D deserved to be D Problem? According to me it should've been Div2 E.</p></div> </div> </div> <div class="reply info"> <a class="comment-808795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808795"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808796" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mangat_angad" style="position: relative;"> <img src='https://userpic.codeforces.org/1449578/avatar/d3cadb0c26e0c11f.jpg'/> </a> <div><a href="/profile/mangat_angad" title="Specialist mangat_angad" class="rated-user user-cyan">mangat_angad</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808796" href="?#comment-808796" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808796" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1449578" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808796"> <div class="moveup"> <div class="ttypography"><p>I feel like such an idiot for not being able to understand problem C (Div2). For some reason I thought the nodes were connected like this — 1-&gt;2-&gt;3-&gt;....-&gt;N and that we had to minimise answer by adding other edges (of negative weight in case they dont give a negative cycle) to this graph.</p></div> </div> </div> <div class="reply info"> <a class="comment-808796 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808796 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808796"> <li> <div class="comment"> <table class="comment-table" commentId="808896" commentParentId="808796"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808896" href="?#comment-808896" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808796" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808896" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808896"> <div class="moveup"> <div class="ttypography"><p>But that's exactly what I did, and the final answer is the sum of the array — sum of all subarrays. <a href="https://codeforces.com/contest/1541/submission/120611950">120611950</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808896 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808896 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808896"> <li> <div class="comment"> <table class="comment-table" commentId="808941" commentParentId="808896"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808941" href="?#comment-808941" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808896" style="font-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="808941" 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="808941" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808941"> <div class="moveup"> <div class="ttypography"><p>No, that's not what you did. To compute the answer via the method described above, you would have to compute how many elements are lesser than the current element at any given iteration and add them and also keep and their count using a Fenwick tree/ BIT. That's the incorrect approach though because sorting would be more optimal.</p></div> </div> </div> <div class="reply info"> <a class="comment-808941 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808941 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808941"> <li> <div class="comment"> <table class="comment-table" commentId="808952" commentParentId="808941"> <tr> <td class="left"> <div style="position: absolute; left: 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/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808952" href="?#comment-808952" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808941" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808952" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808952"> <div class="moveup"> <div class="ttypography"><p>Sorry if I misunderstood things. mangat_angad only mentioned adding negative weighed edges to the 1-&gt;2-&gt;3-&gt;...N graph, which is what I thought to arrive at my solution. The array I mentioned is indeed sorted and formed by distance differences which are the weights in the 1-&gt;2-&gt;3-&gt;...N graph. Unfortunately I'm still too noob to understand the tree structures you mentioned.</p></div> </div> </div> <div class="reply info"> <a class="comment-808952 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808952 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808952"> <li> <div class="comment"> <table class="comment-table" commentId="808955" commentParentId="808952"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808955" href="?#comment-808955" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808952" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808955" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808955"> <div class="moveup"> <div class="ttypography"><p>Nothing unfortunate about it, logic trumps everything </p></div> </div> </div> <div class="reply info"> <a class="comment-808955 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808955 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808955"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808797" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808797" href="?#comment-808797" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808797" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808797"> <div class="moveup"> <div class="ttypography"><p>Just want to apologize to authors for the stupidest question, I misread the task..</p></div> </div> </div> <div class="reply info"> <a class="comment-808797 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808797 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808797"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808813" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808813" href="?#comment-808813" style="font-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="808813" 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="808813" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808813"> <div class="moveup"> <div class="ttypography"><p>Can someone tell me the meaning of this line in problem Div2D/Div1B<br /></p> <blockquote><p>Note that, until reaching, l every possible process still has the same probability of reaching b before a. Therefore, we can assume that the process has reached l and calculate the probability from there.</p> </blockquote><p>What same probability are they talking about?</p></div> </div> </div> <div class="reply info"> <a class="comment-808813 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808813 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808813"> <li> <div class="comment"> <table class="comment-table" commentId="808831" commentParentId="808813"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808831" href="?#comment-808831" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808813" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808831" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808831"> <div class="moveup"> <div class="ttypography"><p>Here's what it's trying to say:</p><p>Suppose we start by marking the root. To mark a or b, we must first mark the lca, so we may assume that the lca has just been marked.</p></div> </div> </div> <div class="reply info"> <a class="comment-808831 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808831 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808831"> <li> <div class="comment"> <table class="comment-table" commentId="808840" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808840" href="?#comment-808840" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808840" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808840"> <div class="moveup"> <div class="ttypography"><p>And what does this line mean? <em>&quot;The problem can be rephrased as having two stacks of size dist(l,a) and dist(l,b) with an arbitrary p to remove a node from one of the two stack (and 1−2p to nothing) and finding the probability that dist(l,b) reaches zero before dist(l,a).&quot;</em></p></div> </div> </div> <div class="reply info"> <a class="comment-808840 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808840 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808840"> <li> <div class="comment"> <table class="comment-table" commentId="808857" commentParentId="808840"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808857" href="?#comment-808857" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808840" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808857" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808857"> <div class="moveup"> <div class="ttypography"><p>Once you've reached the lca $$$l$$$, in a single step you either step closer to $$$a$$$, step closer to $$$b$$$, or step closer to neither.</p></div> </div> </div> <div class="reply info"> <a class="comment-808857 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808857 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808857"> <li> <div class="comment"> <table class="comment-table" commentId="808862" commentParentId="808857"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808862" href="?#comment-808862" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808857" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808862" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808862"> <div class="moveup"> <div class="ttypography"><p>Can you add implementation for this problem please?</p></div> </div> </div> <div class="reply info"> <a class="comment-808862 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808862 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808862"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808849" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808849" href="?#comment-808849" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808849" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808849"> <div class="moveup"> <div class="ttypography"><p>So, we mark lca first (of course). But why wouldn't it affect the final probability of reaching b before a? I mean, why is it sufficient to calculate the probability after marking lca?</p></div> </div> </div> <div class="reply info"> <a class="comment-808849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808849"> <li> <div class="comment"> <table class="comment-table" commentId="808873" commentParentId="808849"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808873" href="?#comment-808873" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808849" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808873" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808873"> <div class="moveup"> <div class="ttypography"><p>Before marking the lca, there is no way to make more progress towards $$$b$$$ than $$$a$$$ or vice versa. The subset of marked vertices also does not change the probability of moving towards $$$a$$$ or $$$b$$$ after reaching the lca because we're choosing uniformly at random and exactly two vertices are of interest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808873 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808873 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808873"> <li> <div class="comment"> <table class="comment-table" commentId="808883" commentParentId="808873"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808883" href="?#comment-808883" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808873" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808883" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808883"> <div class="moveup"> <div class="ttypography"><p>Now I get it. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808883 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808883 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808883"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808814" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808814" href="?#comment-808814" style="font-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="808814" 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="808814" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808814"> <div class="moveup"> <div class="ttypography"><p>So, my Solution for <strong>Div1 Problem B</strong> / <strong>Div2 Problem D</strong> / <strong>1540B — Tree Array</strong>:</p><p>Chose two Nodes $$$A$$$ and $$$B$$$ with $$$A&gt;B$$$. </p><p><strong>First DFS:</strong> Find the path from $$$A$$$ to $$$B$$$. I call it $$$path_p$$$. On $$$path_p$$$ mark the distance to $$$B$$$ for each node. </p><p><strong>Second DFS:</strong> For each remaining node $$$N$$$ find the shortest path to $$$path_p$$$. It will hit it at some node of the $$$path_p$$$ which has some distance $$$D$$$ marked on it. We mark $$$N$$$ with $$$D$$$. (See comment below for image.)</p><p><strong>Calculation:</strong> For each node $$$N$$$ we can calculate $$$P_i$$$. $$$P_i$$$ is the probability to reach Node $$$B$$$ before we reach Node $$$A$$$. We sum $$$P_i$$$ for each node. $$$P_i$$$ is also the probability, that the pair of Nodes $$$A$$$ and $$$B$$$ with starting node $$$N$$$ will contribute to the inversion sum. </p><p><strong>Iteration:</strong> We need to repeat this for each pair $$$A$$$ and $$$B$$$. In the end we divide the answer by $$$n$$$, the amount of nodes (the probability to start with Node $$$N$$$). </p><p>This algorithm is $$$O(N^3)$$$. See my Solution <a href="/contest/1540/submission/120603369" title="Посылка 120603369 от OleschY">120603369</a></p> <div class="spoiler"><b class="spoiler-title">How to calculate P_i</b><div class="spoiler-content" style="display: none;"><p>I wrote myself a small helper DP-program to find the regularities. Let $$$D$$$ be the Distance between $$$A$$$ and $$$B$$$ and $$$d$$$ be the distance from the node $$$N$$$ to $$$B$$$. My educated guess was: $$$P_i=\frac{\sum_{i=0}^{d-1}\binom{D-1}{i} }{2^{D-1}}$$$</p> <div class="spoiler"><b class="spoiler-title">Helper Program</b><div class="spoiler-content" style="display: none;"><p>It checks for a path of some length for each Intervall $$$[A,B]$$$ which is already visited, what the probability to reach one node before the other is. </p> <pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; int solve(int n) { vector&lt;vector&lt;double&gt;&gt; dp(n, vector&lt;double&gt;(n, 0)); for(int i = 0; i &lt; n; ++i) { dp[0][i] = 1; dp[i][n - 1] = 0; } dp[0][n - 1] = -1; for(int w = n; w &gt;= 0; w--) { for(int i = 1; i + w &lt; n - 1; i++) { int l = i; int r = w + i; dp[l][r] = 0.5 * (dp[l - 1][r] + dp[l][r + 1]); } } cout &lt;&lt; n &lt;&lt; &quot;\n\n&quot;; for(int i = 0; i &lt; n; i++) { cout &lt;&lt; dp[i][i]*(1&lt;&lt;(n-2)) &lt;&lt; &quot;\n&quot;; } cout &lt;&lt; &quot;\n\n\n\n&quot;; return 0; } //====================== // Technical stuff //====================== int main() { int ntest = 12; for(int test = 2; test &lt; ntest; ++test) { solve(test); } return 0; } </code></pre></div></div></div></div></div> </div> </div> <div class="reply info"> <a class="comment-808814 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808814 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808814"> <li> <div class="comment"> <table class="comment-table" commentId="808843" commentParentId="808814"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808843" href="?#comment-808843" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808814" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808843" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808843"> <div class="moveup"> <div class="ttypography"><p>Can you explain your solution in a little bit more detail? :')</p></div> </div> </div> <div class="reply info"> <a class="comment-808843 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808843 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808843"> <li> <div class="comment"> <table class="comment-table" commentId="808869" commentParentId="808843"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808869" href="?#comment-808869" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808843" style="font-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="808869" 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="808869" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808869"> <div class="moveup"> <div class="ttypography"><p>Oof, I can give you an image, that shows how the distances from the two DFS are distributed on an example. You can see Nodes $$$A$$$ and $$$B$$$ and the numbers are the distances we write into the nodes. </p><p><img alt=" " src="/predownloaded/d8/2f/d82f98ecd2c1b4bd15b3c40e62476f6ae2741a64.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>If you have specific questions about some steps go ahead and ask. </p></div> </div> </div> <div class="reply info"> <a class="comment-808869 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808869 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808869"> <li> <div class="comment"> <table class="comment-table" commentId="810069" commentParentId="808869"> <tr> <td class="left"> <div style="position: absolute; left: 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/Mrajaryan" style="position: relative;"> <img src='https://userpic.codeforces.org/1377953/avatar/e904b3a3a2eac1ad.jpg'/> </a> <div><a href="/profile/Mrajaryan" title="Newbie Mrajaryan" class="rated-user user-gray">Mrajaryan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 15:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810069" href="?#comment-810069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808869" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810069" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1377953" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810069"> <div class="moveup"> <div class="ttypography"><p>what does the dp states mean in your helper program? I am unable to understand. Can you please explain?</p></div> </div> </div> <div class="reply info"> <a class="comment-810069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810069"> <li> <div class="comment"> <table class="comment-table" commentId="810097" commentParentId="810069"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 18:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810097" href="?#comment-810097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-810069" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810097"> <div class="moveup"> <div class="ttypography"><p>You have Nodes $$$1$$$ through $$$N$$$, neighbouring IDs are connected. The state $$$dp[l][r]$$$ is the probability, that node $$$N$$$ will be reached before node $$$1$$$ with all the nodes $$$l$$$ through $$$r$$$ marked already. Obviously $$$dp[1][x]=0$$$ and $$$dp[x][N]=1$$$ ($$$dp[1][N]$$$ can't happen). The recurrence is $$$dp[l][r]=(dp[l-1][r]+dp[l][r+1])/2$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-810097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808818" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808818" href="?#comment-808818" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808818" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808818"> <div class="moveup"> <div class="ttypography"><p>I can't grasp the editorial of Div 2 D/ Div 1 B. Can somebody provide a more intuitive explanation?</p></div> </div> </div> <div class="reply info"> <a class="comment-808818 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808818 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808818"> <li> <div class="comment"> <table class="comment-table" commentId="808821" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:45">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808821" href="?#comment-808821" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808821" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808821"> <div class="moveup"> <div class="ttypography"><p>same :(</p></div> </div> </div> <div class="reply info"> <a class="comment-808821 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808821 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808821"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808861" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808861" href="?#comment-808861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808861" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808861"> <div class="moveup"> <div class="ttypography"><p>Step 1. use linearity of expectation. The answer is</p> <center>$$$\sum_{a&lt;b} P(b\text{ appears before }a). $$$</center><p>Step 2: Observe that if we start by marking a vertex $$$c$$$ on the path between $$$a$$$ and $$$b$$$, and suppose the next marked vertex on the path is $$$d$$$. Then, the probability that $$$d$$$ is between $$$c$$$ and $$$a$$$ and the probability that $$$d$$$ is between $$$c$$$ and $$$b$$$ are both $$$1/2$$$. This is because there are only two choices for $$$d$$$ and we're choosing uniformly at random. This means that the answer only depends on $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p><p>Step 3: run a dp to calculate the probability that we mark $$$b$$$ before $$$a$$$ given $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808861"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808833" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808833" href="?#comment-808833" style="font-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="808833" 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="808833" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-72" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-72</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808833"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin &gt;&gt; t; while(t--){ int n; cin &gt;&gt; n; long long arr[n]; for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0; for(int i = 0; i &lt; n — 1; i++){ for(int j = arr[i] — 2 — i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } } } cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;; } return 0; }</p><p>/* Accepted code A different approach using arrays (as I don't know what vectors are, haven't read that) I hope this is a optimal approach. Any suggestions related to this are whole-heartedly welcomed. Also, please guide me how could I have optimized the code to a much extent. Thanks in advance! Keep programming! */</p></div> </div> </div> <div class="reply info"> <a class="comment-808833 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808833 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808833"> <li> <div class="comment"> <table class="comment-table" commentId="808844" commentParentId="808833"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808844" href="?#comment-808844" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808833" style="font-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="808844" 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="808844" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-35" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808844"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-808844 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808844 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808844"> <li> <div class="comment"> <table class="comment-table" commentId="808863" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808863" href="?#comment-808863" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808863" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808863"> <div class="moveup"> <div class="ttypography"><p>Not studied yet, I'm still a beginner, but planning to start soon. Thanks for the guidance.</p></div> </div> </div> <div class="reply info"> <a class="comment-808863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808863"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808879" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808879" href="?#comment-808879" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808879" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808879"> <div class="moveup"> <div class="ttypography"><p>once upon a time, I also did problems while not know what vectors are. sad times :'(</p></div> </div> </div> <div class="reply info"> <a class="comment-808879 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808879 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808879"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808926" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808926" href="?#comment-808926" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808926" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808926"> <div class="moveup"> <div class="ttypography"><p>There's no issue in not knowing vectors. Yes they are important I agree but not knowing vectors should not be discouraged. I became expert here without knowing anything about vectors plus he is a beginner so he shouldn't be discouraged like this.</p></div> </div> </div> <div class="reply info"> <a class="comment-808926 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808926 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808926"> <li> <div class="comment"> <table class="comment-table" commentId="808927" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Tech.Maniac" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Tech.Maniac" title="Expert Tech.Maniac" class="rated-user user-blue">Tech.Maniac</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808927" href="?#comment-808927" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808927" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1242860" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808927"> <div class="moveup"> <div class="ttypography"><p>+1, I agree with you. Same I was expert last year solely using arrays</p></div> </div> </div> <div class="reply info"> <a class="comment-808927 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808927 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808927"> <li> <div class="comment"> <table class="comment-table" commentId="809201" commentParentId="808927"> <tr> <td class="left"> <div style="position: absolute; left: 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/Yash.Amin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Yash.Amin" title="Specialist Yash.Amin" class="rated-user user-cyan">Yash.Amin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809201" href="?#comment-809201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808927" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809201" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-28" data-commentUserId="1226462" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-28</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809201"> <div class="moveup"> <div class="ttypography"><p>Bas kar bsdk kitna jhooth bolega</p></div> </div> </div> <div class="reply info"> <a class="comment-809201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809201"> <li> <div class="comment"> <table class="comment-table" commentId="809215" commentParentId="809201"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809215" href="?#comment-809215" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809215" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809215"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-blue" href="/profile/Yash.Amin" title="Эксперт Yash.Amin">Yash.Amin</a> Could you please refrain from using foul language on educational discussions. Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-809215 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809215 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809215"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808928" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808928" href="?#comment-808928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808928" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808928"> <div class="moveup"> <div class="ttypography"><p>Ah my bad, I did not want to come across as being arrogant, but I was genuinely confused that some people did not know vectors although they are using C++.</p></div> </div> </div> <div class="reply info"> <a class="comment-808928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808928"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808839" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamkiller04" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dreamkiller04" title="Newbie dreamkiller04" class="rated-user user-gray">dreamkiller04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808839" href="?#comment-808839" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2089608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808839"> <div class="moveup"> <div class="ttypography"><p>Please add implementations too.</p></div> </div> </div> <div class="reply info"> <a class="comment-808839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808839"> <li> <div class="comment"> <table class="comment-table" commentId="809106" commentParentId="808839"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809106" href="?#comment-809106" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808839" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809106" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809106"> <div class="moveup"> <div class="ttypography"><p>Simply running two loops and checking every case would give a TLE. So, we might want to minimize the number of operations. For this, we would only consider the cases where the sum of indices is a multiple of an element.</p><p>For this, we would first create two loops, one within the other, first loop iterating i from 0 to (n — 1) with an incrementation of 1. By observation, we can see that the first index for which the sum of indices will be a multiple of arr[i] is (arr[i] — 2 — i).</p><p>So, in the nested loop we will run j = (arr[i] — 2 — i) till (n — 1) with an incrementation of arr[i]. We would ignore the cases where j &lt; 0 or j &gt;= n.</p><p>Finally, we need to check for how many cases this holds (arr[i] * arr[j] = i + j + 2 and j &gt; i).</p><p>Suggestions are welcomed!</p></div> </div> </div> <div class="reply info"> <a class="comment-809106 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809106 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809106"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808842" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808842" href="?#comment-808842" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808842" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-64" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-64</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808842"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){</p><p>ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);</p><p>int t;</p><p>cin &gt;&gt; t;</p><p>while(t--){</p><p>int n;</p> <pre>cin &gt;&gt; n;</pre><p>long long arr[n];</p> <pre>for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0;</pre><p>for(int i = 0; i &lt; n — 1; i++){</p> <pre>for(int j = arr[i] &amp;mdash; 2 &amp;mdash; i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } }</pre><p>}</p><p>cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;;</p><p>}</p> <pre>return 0;</pre><p>}</p><p>/* Accepted code</p><p>A different approach using arrays (as I don't know what vectors are, haven't read that)</p><p>I hope this is a optimal approach.</p><p>Any suggestions related to this are whole-heartedly welcomed.</p><p>Also, please guide me how could I have optimized the code to a much extent.</p><p>Thanks in advance!</p><p>Keep programming! </p><p>*/</p></div> </div> </div> <div class="reply info"> <a class="comment-808842 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808842 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808842"> <li> <div class="comment"> <table class="comment-table" commentId="808851" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808851" href="?#comment-808851" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808851" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808851"> <div class="moveup"> <div class="ttypography"><p>Use spoilers for writing codes, please!</p></div> </div> </div> <div class="reply info"> <a class="comment-808851 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808851 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808851"> <li> <div class="comment"> <table class="comment-table" commentId="808870" commentParentId="808851"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808870" href="?#comment-808870" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808851" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808870" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808870"> <div class="moveup"> <div class="ttypography"><p>Actually, this is my first comment. Don't know much of this stuff as of now, but I'll surely take care of it the very next time.</p></div> </div> </div> <div class="reply info"> <a class="comment-808870 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808870 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808870"> <li> <div class="comment"> <table class="comment-table" commentId="809760" commentParentId="808870"> <tr> <td class="left"> <div style="position: absolute; left: 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/sus" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sus" title="Pupil sus" class="rated-user user-green">sus</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 05:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809760" href="?#comment-809760" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808870" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809760" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1749651" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809760"> <div class="moveup"> <div class="ttypography"><p>what problem is your code for</p></div> </div> </div> <div class="reply info"> <a class="comment-809760 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809760 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809760"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808884" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sevlll777" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sevlll777" title="Grandmaster sevlll777" class="rated-user user-red">sevlll777</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808884" href="?#comment-808884" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808884" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="839333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808884"> <div class="moveup"> <div class="ttypography"><p>NICE CODESTYLE!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-808884 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808884 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808884"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809084" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cj2021" style="position: relative;"> <img src='https://userpic.codeforces.org/1927237/avatar/b64ff59bd9dcf385.jpg'/> </a> <div><a href="/profile/cj2021" title="Newbie cj2021" class="rated-user user-gray">cj2021</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809084" href="?#comment-809084" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809084" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1927237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809084"> <div class="moveup"> <div class="ttypography"><p>What is &amp;mdash?</p><p>Just curious to know as haven't seen it before.</p></div> </div> </div> <div class="reply info"> <a class="comment-809084 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809084 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809084"> <li> <div class="comment"> <table class="comment-table" commentId="809097" commentParentId="809084"> <tr> <td class="left"> <div style="position: absolute; left: 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/klahsiv" style="position: relative;"> <img src='https://userpic.codeforces.org/1590145/avatar/1bf86ae3d48e55b.jpg'/> </a> <div><a href="/profile/klahsiv" title="Expert klahsiv" class="rated-user user-blue">klahsiv</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809097" href="?#comment-809097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809084" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590145" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809097"> <div class="moveup"> <div class="ttypography"><p>it is minus (-).</p></div> </div> </div> <div class="reply info"> <a class="comment-809097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808848" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/willy108" style="position: relative;"> <img src='https://userpic.codeforces.org/1439320/avatar/d7f79ed4e8b32e9a.jpg'/> </a> <div><a href="/profile/willy108" title="Master willy108" class="rated-user user-orange">willy108</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808848" href="?#comment-808848" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808848" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="1439320" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808848"> <div class="moveup"> <div class="ttypography"><p>Div2 B can also be done in O(NsqrtN). We know that for a given pair of indeces i+j &lt; 2n, so any pair that a[i] * a[j] &lt; 2n will have to have one of the two terms be &lt;= sqrt(n) (with some off by one errors of course). So the algorithm is to store an array of pairs [array value, index] and sort that array by the value. If the array value is &lt;= sqrt(2n) we can naively loop over the rest of the array in O(n) time and check (be careful about overcount), and if the value is &gt; sqrt(n), we can ignore it. This works since when a[i] * a[j] &lt; 2n one of a[i] or a[j] has to be &lt;= sqrt(2n) and as a result, every pair will be counted.</p></div> </div> </div> <div class="reply info"> <a class="comment-808848 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808848 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808848"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808860" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bcollet" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bcollet" title="Master bcollet" class="rated-user user-orange">bcollet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808860" href="?#comment-808860" style="font-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="808860" 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="808860" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="858059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808860"> <div class="moveup"> <div class="ttypography"><p>I don't understand in div1 C why it's prefix of b, in the case i=3 we have $$$a_1+a_2+a_3=f_1+f_1+b_1+f_1+b_1+b_2$$$ so $$$f_1=(ap_i-2b_1-b_2)$$$ I believe the general formula is something in the taste of $$$f_1=(ap_i-ibp_{i-1}+bpt_{i-1})/i$$$ where bpt_i=b_1+2b_2+...+ib_i, I think I miss something<br />Edit: corrected</p></div> </div> </div> <div class="reply info"> <a class="comment-808860 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808860 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808860"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808865" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ParsaS" style="position: relative;"> <img src='https://userpic.codeforces.org/1590150/avatar/dc2d8c002d2c5e1e.jpg'/> </a> <div><a href="/profile/ParsaS" title="Candidate Master ParsaS" class="rated-user user-violet">ParsaS</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808865" href="?#comment-808865" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808865" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590150" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808865"> <div class="moveup"> <div class="ttypography"><p>Nice problems. thanks for almost fast editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-808865 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808865 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808865"> <li> <div class="comment"> <table class="comment-table" commentId="808871" commentParentId="808865"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/E404_Not_Found" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/E404_Not_Found" title="Expert E404_Not_Found" class="rated-user user-blue">E404_Not_Found</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808871" href="?#comment-808871" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808865" style="font-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="808871" 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="808871" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1662858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808871"> <div class="moveup"> <div class="ttypography"><p>Yes thanks for fast editorial :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808871 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808871 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808871"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808890" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vikash_8090_b" style="position: relative;"> <img src='https://userpic.codeforces.org/1969032/avatar/a0f23c893ae54e74.jpg'/> </a> <div><a href="/profile/vikash_8090_b" title="Newbie vikash_8090_b" class="rated-user user-gray">vikash_8090_b</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808890" href="?#comment-808890" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808890" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="1969032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808890"> <div class="moveup"> <div class="ttypography"><p>is there anyone who can't even solve one question of today's contest ..</p></div> </div> </div> <div class="reply info"> <a class="comment-808890 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808890 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808890"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808892" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808892" href="?#comment-808892" style="font-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="808892" 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="808892" class="CommentVoteFrame" data-commentRating="-6" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808892"> <div class="moveup"> <div class="ttypography"><p>Deleted :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808892 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808892 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808892"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808918" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prituladima" style="position: relative;"> <img src='https://userpic.codeforces.org/116750/avatar/ca46d0256a294b26.jpg'/> </a> <div><a href="/profile/prituladima" title="Pupil prituladima" class="rated-user user-green">prituladima</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808918" href="?#comment-808918" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808918" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="116750" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808918"> <div class="moveup"> <div class="ttypography"><p>Please explain div2c/div1a problem a little bit more. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808918 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808918 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808918"> <li> <div class="comment"> <table class="comment-table" commentId="808921" commentParentId="808918"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808921" href="?#comment-808921" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808918" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808921" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808921"> <div class="moveup"> <div class="ttypography"><p>Try out this <a href="https://youtube.com/c/MagentaCobra">channel</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808921 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808921 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808921"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808950" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jakab922" style="position: relative;"> <img src='https://userpic.codeforces.org/53532/avatar/f9515e974f3ebcb1.jpg'/> </a> <div><a href="/profile/jakab922" title="Specialist jakab922" class="rated-user user-cyan">jakab922</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808950" href="?#comment-808950" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808950" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="53532" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808950"> <div class="moveup"> <div class="ttypography"><p>I don't really understand the need for a recursive function for the stack emptying probabilities in <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a>. I mean given that you have a stack of size <code>n</code> and and <code>m</code> you can basically have an array of size <code>n + m</code> filled with <code>0</code>s and <code>1</code>s where <code>0</code> at the <code>i</code>th place means that the <code>i</code>th element was taken from the first stack. Any such array which has <code>n</code> <code>0</code>s and <code>m</code> <code>1</code>s correspond to one process and it's easy to see that whoever takes the last spot in the array gets emptied later which gives an easy way to calculate the probabilities. Namely $$$\binom{n + m - 1}{n - 1} / \binom{n + m}{n}$$$ for the first and similar to the other. </p></div> </div> </div> <div class="reply info"> <a class="comment-808950 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808950 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808950"> <li> <div class="comment"> <table class="comment-table" commentId="808959" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cuom1999" style="position: relative;"> <img src='https://userpic.codeforces.org/253776/avatar/934152bc42a0b10c.jpg'/> </a> <div><a href="/profile/cuom1999" title="Grandmaster cuom1999" class="rated-user user-red">cuom1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808959" href="?#comment-808959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="253776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808959"> <div class="moveup"> <div class="ttypography"><p>If $$$m=2$$$ and $$$n=1$$$, your approach gives $$$\frac{1}{3}$$$. The correct answer should be $$$\frac{1}{4}$$$. </p><p>P/S: I'm also curious if there is any combinatoric approach for this,<a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808959"> <li> <div class="comment"> <table class="comment-table" commentId="809004" commentParentId="808959"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809004" href="?#comment-809004" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809004" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809004"> <div class="moveup"> <div class="ttypography"><p>I would guess that there’s no easy closed form. You can evaluate in $$$O(n)$$$ however by counting right up paths from $$$(a,0)$$$ to $$$(x,y)$$$ for all $$$a$$$ and multiplying by $$$2^{-steps}$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-809004 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809004 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809004"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809366" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/geekpradd" style="position: relative;"> <img src='https://userpic.codeforces.org/367430/avatar/427394aa7f5a63a0.jpg'/> </a> <div><a href="/profile/geekpradd" title="Candidate Master geekpradd" class="rated-user user-violet">geekpradd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809366" href="?#comment-809366" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809366" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="367430" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809366"> <div class="moveup"> <div class="ttypography"><p>The problem with this is that all the possibilities are not equilikely, consider $$$m=2, n=1$$$ and let $$$1$$$ denote entries from the stack of size $$$n$$$. Then the probability of obtaining $$$100$$$ is $$$1/2$$$, while obtaining $$$010$$$ and $$$001$$$ has a probability of $$$1/4$$$. Your approach assumes a uniform prior probability (in which case the answer is indeed $$$1/3$$$ whereas here it is $$$1/4$$$ which is the probability of getting $$$001$$$)</p></div> </div> </div> <div class="reply info"> <a class="comment-809366 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809366 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809366"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thunderboltz" style="position: relative;"> <img src='https://userpic.codeforces.org/1170396/avatar/4f017b259605bc5c.jpg'/> </a> <div><a href="/profile/thunderboltz" title="Newbie thunderboltz" class="rated-user user-gray">thunderboltz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808951" href="?#comment-808951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170396" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808951"> <div class="moveup"> <div class="ttypography"><p>Problem Div2C/Div1A, Plz somebody explain 3rd hint. I didn't get why this condition must be true </p><p><code>The sum of the values of edges with positive weight must be ≥ the maximum value in the array.</code></p></div> </div> </div> <div class="reply info"> <a class="comment-808951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808951"> <li> <div class="comment"> <table class="comment-table" commentId="808995" commentParentId="808951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808995" href="?#comment-808995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808995" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808995"> <div class="moveup"> <div class="ttypography"><p>I like to think about C this way: The cheapest node is the root, and the most expensive node, X, is the one with the highest value, D. Therefore no matter how we make our edges, we need at least 1 path from node to X with distance D. So let's build 1 single edge of positive weight from 1 to X with weight D.</p><p>Now from node X, all other nodes are &lt;= D. We can use negative edges to go there. Now the problem just becomes &quot;assign as many negative edges as possible&quot; to the rest of the nodes. </p></div> </div> </div> <div class="reply info"> <a class="comment-808995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808995"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808971" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808971" href="?#comment-808971" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808971" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808971"> <div class="moveup"> <div class="ttypography"><p>In problem <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a> I agree with everything up to:</p> <blockquote><p>Once l is reached, we now note that the probability that the process &quot;gets closer&quot; to b is always equal to the probability of getting closer to a.</p> </blockquote><p>I agree with this quote if it was about each individual set of marked nodes and single step for them. Because for any individual set of marked nodes, those probabilities is just one over the number of options at the moment. But I don't understand why I should forget about everything else what happens with other parts of tree, because after single step which is neither towards <strong>a</strong> neither towards <strong>b</strong>, the number of options (nodes we can mark on next step) may change.</p></div> </div> </div> <div class="reply info"> <a class="comment-808971 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808971 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808971"> <li> <div class="comment"> <table class="comment-table" commentId="809006" commentParentId="808971"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809006" href="?#comment-809006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808971" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809006" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809006"> <div class="moveup"> <div class="ttypography"><p>That is correct, but to see how it stays the same you can think of it inductively. Use strong induction and assume probability is the same no matter what the state of the tree is. Then from $$$(x,y)$$$ you always have an equal probability of ending up in one of the two states you can transition to because $$$p$$$ is always the same. Every scenario you enter one state, there’s another scenario with the same probability that enters the other state. So, the probability of entering one of the two states is the same as the other, thus $$$0.5$$$. Hopefully that makes things more clear.</p></div> </div> </div> <div class="reply info"> <a class="comment-809006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809006"> <li> <div class="comment"> <table class="comment-table" commentId="809113" commentParentId="809006"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809113" href="?#comment-809113" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809006" style="font-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="809113" 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="809113" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809113"> <div class="moveup"> <div class="ttypography"><p>Oh thanks, it's clear now. So, base of induction is when only <strong>l</strong> reached, and we can show that probability to make step towards <strong>a</strong> and <strong>b</strong> is same because for each individual set you can go from <strong>l</strong> to <strong>b</strong> instead of going from <strong>l</strong> into <strong>a</strong>, using exactly same steps in between (those steps which doesn't change distances to <strong>a</strong> and <strong>b</strong>). And similar holds for next steps.</p></div> </div> </div> <div class="reply info"> <a class="comment-809113 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809113 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809113"> <li> <div class="comment"> <table class="comment-table" commentId="821713" commentParentId="809113"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 08:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821713" href="?#comment-821713" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809113" style="font-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="821713" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="821713" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-821713"> <div class="moveup"> <div class="ttypography"><p>Can you explain this?</p><p>Assume $$$X$$$ is initially node we chose. Then define a function $$$g$$$ :</p><p>$$$g[a][b][STATE]$$$ = probability to reach a before b while state of the tree we reach is $$$STATE$$$, and $$$a$$$, $$$b$$$ is length of path.</p><p><img alt=" " src="/predownloaded/c2/32/c232d053fe3fbd1dedc06e56db58a7c139157987.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>follow the image, I can see : $$$g[a][b][STATE_x] = \frac{1}{4} (g[a][b][STATE_d] + g[a][b][STATE_e] + g[a — 1][b][closer_a] + g[a][b — 1][closer_b])$$$</p><p>It can easy see that the probability can change. Or I wrong in some where?</p></div> </div> </div> <div class="reply info"> <a class="comment-821713 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821713 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821713"> <li> <div class="comment"> <table class="comment-table" commentId="821861" commentParentId="821713"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 18:25">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821861" href="?#comment-821861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821713" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="821861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-821861"> <div class="moveup"> <div class="ttypography"><p>I'll hide my long explanation under spoiler</p> <div class="spoiler"><b class="spoiler-title">horrible wall of text</b><div class="spoiler-content" style="display: none;"><p>To put things into words, I want to define some things. First, suppose we marked some $$$s_1, s_2, s_3 ... s_k$$$ vertices in exact this order. Then, let $$$P(s)$$$ to be probability to mark them in this sequence. It can be decomposed into $$$P(s) = p_1 \cdot p_2 \cdot p_3 \cdot ... \cdot p_k$$$ where $$$p_i = 1/o_{i-1}$$$ where $$$o_i$$$ is number of options at step $$$i$$$ — number of opened vertices, except $$$p_0 = 1/n$$$, or $$$o_0 = n$$$.</p><p>Then, let $$$l = LCA(a, b)$$$ where $$$LCA$$$ is lowest common ancestor. Then, let $$$x_v$$$ to be some sort of 'cost'. For each $$$v$$$ on path between $$$a$$$ and $$$l$$$ it will be distance to $$$l$$$, and $$$-1$$$ everywhere else. Similarly, for each $$$v$$$ on path between $$$b$$$ and $$$l$$$ let $$$y_v$$$ to be distance to $$$l$$$ and $$$-1$$$ everywhere else. Let</p> <center>$$$ A(s) = \max\limits_{v\in s}x_v \\ B(s) = \max\limits_{v\in s}y_v $$$</center><p>Then $$$A(s)$$$ is equal to how far we reach $$$a$$$, and $$$B(s)$$$ is equal to how far we reach $$$b$$$. Let say we are in situation $$$(A(s), B(s))$$$ after marking $$$s$$$, and therefore situation is pair of numbers. Situation $$$(-1,-1)$$$ corresponds that no vertex is marked on path from $$$a$$$ to $$$b$$$. Situation $$$(0,0)$$$ corresponds to only $$$l$$$ marked on path from $$$a$$$ to $$$b$$$. And situation $$$(1,0)$$$ corresponds to $$$l$$$ and single vertex towards $$$a$$$ is marked.</p><p>Finally, let say sequence of marks $$$s$$$ reached state $$$(A(s), B(s))$$$ if either $$$A(s) = x_{s_k}$$$ or $$$B(s) = y_{s_k}$$$, in other words, last vertex is on path from $$$a$$$ to $$$b$$$ and it did change situation.</p><p>Now, what we want to prove is following:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha+1,\beta)} P(s) = \sum\limits_{s\;reached\;(\alpha,\beta+1)} P(s)$$$</center><p><strong>For some fixed</strong> $$$s_1$$$, which is root we chosen. And the way we prove it is that $$$s$$$ that is reached $$$(\alpha+1,\beta)$$$ consists of $$$u$$$ that reached $$$(\alpha,\beta)$$$ plus additional steps: $$$w$$$ plus $$$s_k$$$. So $$$s = u..w..s_k$$$ where $$$..$$$ is concatenation. It's easy to see what none of vertices from $$$w$$$ is on path from $$$a$$$ to $$$b$$$. Also, it's easy to see that we could instead of choosing $$$s_k$$$ could choose vertex $$$z$$$ towards $$$b$$$, and it would have same probability. In other words $$$P(s) = P(u..w..z)$$$. And this $$$u..w..z$$$ should reach state $$$(\alpha, \beta+1)$$$. So it should be in right side sum of our equation we want to prove.</p><p>So, for any $$$s$$$ from left sum, we can make $$$s'$$$ from right sum in unique way, and it will have same $$$P(s) = P(s')$$$. Similarly, for any $$$s$$$ from right sum, we can make $$$s'$$$ from left sum in unique way, and it will have same $$$P(s) = P(s')$$$. So this is bijection, and each element from left sum corresponds to element from right sum with same value, so those sums should have same value. Therefore it's equality.</p><p>Initially I wanted to trim $$$s$$$ from $$$(\alpha+1,\beta)$$$ to $$$(\alpha,\beta)$$$ and show similar thing based on following sum:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha,\beta)} P(s)$$$</center><p>Which is probability to reach state $$$(\alpha, \beta)$$$, but luckily it didn't required. I'll use notation $$$P(reach(\alpha, \beta))$$$ for this probability.</p><p>Thing that is not covered though: why this equality can be translated into probability $$$= 1/2$$$? Well, from $$$(\alpha, \beta)$$$ you eventually will reach either $$$(\alpha+1,\beta)$$$ or $$$(\alpha,\beta+1)$$$, so you can see this as example of Law of total probability. $$$P(reach(\alpha, \beta)) = P(reach (\alpha+1, \beta)) + P(reach (\alpha, \beta+1))$$$, because events $$$(\alpha+1,\beta)$$$ and $$$(\alpha,\beta+1)$$$ are disjoint events given $$$(\alpha, \beta)$$$ is reached. And we proved they have equal probability so $$$P(reach(\alpha, \beta)) = 2\cdot P(reach (\alpha+1, \beta))$$$, so $$$P(reach (\alpha+1, \beta)) = 1/2\cdot P(reach(\alpha, \beta))$$$ which we actually use.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-821861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821861"> <li> <div class="comment"> <table class="comment-table" commentId="822027" commentParentId="821861"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/28/2021 13:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822027" href="?#comment-822027" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821861" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="822027" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822027"> <div class="moveup"> <div class="ttypography"><p>Oh, sorry, there is one missing part. We proved $$$P(reached(\alpha+1,\beta))=P(reached(\alpha,\beta+1))$$$ <strong>given</strong> $$$(\alpha,\beta)$$$ is reached, but this is actually what we need. This <strong>given</strong> condition is what I missed. Without <strong>given</strong> we could reach $$$(\alpha+1,\beta)$$$ from reaching $$$(\alpha+1,\beta-1)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-822027 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822027 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822027"> <li> <div class="comment"> <table class="comment-table" commentId="822370" commentParentId="822027"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 13:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822370" href="?#comment-822370" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822027" style="font-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="822370" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="822370" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822370"> <div class="moveup"> <div class="ttypography"><p>Thanks for amz explain. I realize that I had some missunderstand in the way we calc $$$P(reach\ A\ before\ B)$$$</p><p>This's exactly what in my mind one day ago: let $$$s = ...a...b...$$$ where $$$a$$$ and $$$b$$$ is node $$$a$$$ and node $$$b$$$, &quot;$$$...$$$&quot; mean some node between them which we chose them in exactly that order, or in other word, $$$s$$$ is state represent what we chose (exact in this order) I think $$$P(reach\ A\ before\ B)$$$ (or $$$P(A&lt;B)$$$) must be calculate in this way :</p><p>$$$P(A&lt;B) = \sum_{\substack{all\ s\ which\ a&lt;b}} P(s)$$$</p><p>But unfortunately, it's wrong (may be, or I still missunderstanding)</p><p>$$$P(A) = \sum_{\substack{all\ B[i]\ \subseteq\ A}} P(B[i])$$$ if and only if all $$$B[i]$$$ are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-822370 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822370 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822370"> <li> <div class="comment"> <table class="comment-table" commentId="822755" commentParentId="822370"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 22:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822755" href="?#comment-822755" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822370" style="font-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="822755" 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="822755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822755"> <div class="moveup"> <div class="ttypography"><p>$$$P(A &lt; B)$$$ in your terms is exactly what we need (if a = A and b = B).</p><p>I don't understand last formula, everything else looks fine.</p><p>And to find $$$P(A &lt; B)$$$ we use fact above and calculate all possible ways to reach $$$a$$$ earlier than $$$b$$$ we use $$$(\alpha, \beta)$$$ states using my notation: you either get $$$\alpha$$$ equal to dist to $$$a$$$ when $$$\beta$$$ = 0, or $$$\beta$$$ = 1, or 2, or 3...</p> <center>$$$ P(A &lt; B) = \\ =\sum\limits_{i=0}^{dist(b,l)}P(reach(dist(a,l),i)\;given\; reached(dist(a,l)-1,i)) \\ = \sum\limits_{i=0}^{dist(b,l)}P(reached(dist(a,l)-1,i))\cdot \frac{1}{2} $$$</center><p>Or you can rephrase task into other task with two kind of balls. What probability to remove all balls of one kind earlier than other, if you pick one or other kind of ball with probability 1/2.</p></div> </div> </div> <div class="reply info"> <a class="comment-822755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822755"> </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="808983" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/xsc" style="position: relative;"> <img src='https://userpic.codeforces.org/343/avatar/9eaf243b1eb8c3d4.jpg'/> </a> <div><a href="/profile/xsc" title="Specialist xsc" class="rated-user user-cyan">xsc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808983" href="?#comment-808983" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808983" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="343" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808983"> <div class="moveup"> <div class="ttypography"><p>Div2 D, O(N^4) solution <a href="/contest/1541/submission/120623566" title="Посылка 120623566 от xsc">120623566</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808983 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808983 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808983"> <li> <div class="comment"> <table class="comment-table" commentId="809278" commentParentId="808983"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DavidXu_JJ" style="position: relative;"> <img src='https://userpic.codeforces.org/2003708/avatar/623dc8036b4e9d72.jpg'/> </a> <div><a href="/profile/DavidXu_JJ" title="Expert DavidXu_JJ" class="rated-user user-blue">DavidXu_JJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809278" href="?#comment-809278" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808983" style="font-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="809278" 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="809278" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2003708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809278"> <div class="moveup"> <div class="ttypography"><p>Your code really helps me a lot in debugging,thanks.</p><p>By the way,it's weired that I get Wrong6 when I try to optimize to O(N^3*logN) by binary search on tree.</p><p>I have tested my function on other online judge and my function seems to be correct.</p></div> </div> </div> <div class="reply info"> <a class="comment-809278 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809278 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809278"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809018" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ducati" style="position: relative;"> <img src='https://userpic.codeforces.org/699102/avatar/eff3c352646e914e.jpg'/> </a> <div><a href="/profile/ducati" title="Grandmaster ducati" class="rated-user user-red">ducati</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 03:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809018" href="?#comment-809018" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809018" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="699102" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809018"> <div class="moveup"> <div class="ttypography"><p>Although Div.2 D is harder than ever, in my opinion, it's such a useful and excellent problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-809018 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809018 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809018"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809046" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KanishkGoel" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/KanishkGoel" title="Expert KanishkGoel" class="rated-user user-blue">KanishkGoel</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809046" href="?#comment-809046" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809046" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1917239" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809046"> <div class="moveup"> <div class="ttypography"><p>Is it usual for people to post solutions online during the contest like this channel? <a href="https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ">https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809046 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809046 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809046"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809051" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809051" href="?#comment-809051" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809051"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain why this submission <a href="/contest/1541/submission/120562335" title="Посылка 120562335 от Karnania7201">120562335</a> is failing for Div2 B? It would be a great help.</p></div> </div> </div> <div class="reply info"> <a class="comment-809051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809051"> <li> <div class="comment"> <table class="comment-table" commentId="809076" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809076" href="?#comment-809076" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809076" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809076"> <div class="moveup"> <div class="ttypography"><p>Bro you did not included the condition that i and j should be different i.e (i != j) because it is given in question that no are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-809076 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809076 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809076"> <li> <div class="comment"> <table class="comment-table" commentId="809079" commentParentId="809076"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:08">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809079" href="?#comment-809079" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809076" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809079" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809079"> <div class="moveup"> <div class="ttypography"><p>I think its covered as I started j from i+1. I tried that explicitly too but it didn't work. I wrote the same idea in a different way and it worked but this kind of implementation is not working.</p></div> </div> </div> <div class="reply info"> <a class="comment-809079 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809079 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809079"> <li> <div class="comment"> <table class="comment-table" commentId="809082" commentParentId="809079"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809082" href="?#comment-809082" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809079" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809082" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809082"> <div class="moveup"> <div class="ttypography"><p>yeah, you are right, I run your code using vector instead of creating memeset it worked fine, i guess there is some problem in that. <a href="https://codeforces.com/contest/1541/submission/120633207">120633207</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809082 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809082 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809082"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809081" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_NICkk" style="position: relative;"> <img src='https://userpic.codeforces.org/1543175/avatar/6084dd87f2c1cad9.jpg'/> </a> <div><a href="/profile/_NICkk" title="Expert _NICkk" class="rated-user user-blue">_NICkk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809081" href="?#comment-809081" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809081" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1543175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809081"> <div class="moveup"> <div class="ttypography"><p>Only fault in your code is that you didn't used memset correctly </p><p>I just changed your memset with this &quot; memset(ind, 0, sizeof(ind)) &quot; and it worked perfectly fine</p></div> </div> </div> <div class="reply info"> <a class="comment-809081 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809081 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809081"> <li> <div class="comment"> <table class="comment-table" commentId="809091" commentParentId="809081"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:37">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809091" href="?#comment-809091" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809081" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809091" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809091"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot to both of you. I shouldn't have used it without properly knowing about it. </p></div> </div> </div> <div class="reply info"> <a class="comment-809091 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809091 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809091"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809064" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vrintle" style="position: relative;"> <img src='https://userpic.codeforces.org/1991777/avatar/24d9007095afbbb6.jpg'/> </a> <div><a href="/profile/vrintle" title="Master vrintle" class="rated-user user-orange">vrintle</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809064" href="?#comment-809064" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809064" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1991777" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809064"> <div class="moveup"> <div class="ttypography"><p>Instead of $$$a_i \cdot a_j \leq 2n$$$, we could also check $$$a_i \cdot a_j \leq i+n$$$ which is a bit faster ($$$ \sim 62ms$$$).</p></div> </div> </div> <div class="reply info"> <a class="comment-809064 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809064 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809064"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809066" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809066" href="?#comment-809066" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809066" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809066"> <div class="moveup"> <div class="ttypography"><p>can anyone explain B. pleasant pairs more easy words?? </p></div> </div> </div> <div class="reply info"> <a class="comment-809066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809066"> <li> <div class="comment"> <table class="comment-table" commentId="809067" commentParentId="809066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809067" href="?#comment-809067" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809067" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809067"> <div class="moveup"> <div class="ttypography"><p>And also what is ask in 3rd question i cant understand what asked in it</p></div> </div> </div> <div class="reply info"> <a class="comment-809067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809067"> <li> <div class="comment"> <table class="comment-table" commentId="809070" commentParentId="809067"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809070" href="?#comment-809070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809067" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809070"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">https://www.youtube.com/watch?v=xCj_ZR5kENo</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809098" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809098" href="?#comment-809098" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809098" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809098"> <div class="moveup"> <div class="ttypography"><p>For those who are searching for a simple solution for great Graphs problems in O (nlogn). <a href="https://codeforces.com/contest/1541/submission/120600816">https://codeforces.com/contest/1541/submission/120600816</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809098 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809098 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809098"> <li> <div class="comment"> <table class="comment-table" commentId="809119" commentParentId="809098"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fjvzr" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/fjvzr" title="Newbie fjvzr" class="rated-user user-gray">fjvzr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809119" href="?#comment-809119" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809098" style="font-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="809119" 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="809119" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1623986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809119"> <div class="moveup"> <div class="ttypography"><p>Bro can u explain this soln????? i thought of taking all pairs that give negative edges except for the adjacent pairs.... bt getting wrong ans in 3rd 4th test case.....</p><p>while(n&gt;2) { sum-=(n-2)*(llabs(a[j]-a[i])); n--; // n = size i++; // i = 0 j--; // j = n-1 } cout&lt;&lt;sum&lt;&lt;endl;</p><p><a href="https://codeforces.com/contest/1541/submission/120636509">mysoln</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809119 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809119 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809119"> <li> <div class="comment"> <table class="comment-table" commentId="809124" commentParentId="809119"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809124" href="?#comment-809124" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809119" style="font-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="809124" 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="809124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809124"> <div class="moveup"> <div class="ttypography"><p>My solution is simple. First sort the array. </p><p>Then start connecting adjacent values with their differences. This way sum of all edges with positive weight will be same as the sum of adjacent differences in the array.</p><p>After that start making negative edges for every i. So each i will have i negative edges. Where negative weight is same as -(arr[i] — arr[j]).</p><p>Instead of search it for every j I have formula as (prefixsum till i) — arr[i]*i</p></div> </div> </div> <div class="reply info"> <a class="comment-809124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809124"> <li> <div class="comment"> <table class="comment-table" commentId="809132" commentParentId="809124"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809132" href="?#comment-809132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809124" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809132"> <div class="moveup"> <div class="ttypography"><p>can you tell me why are we sorting the array for a particular node call it x we need to add a negative weight from x to 1 , x to 2 x to 3 till x to x-1 keeping in mind the the path sum doesn't become negative so why are we sorting the array</p></div> </div> </div> <div class="reply info"> <a class="comment-809132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809132"> <li> <div class="comment"> <table class="comment-table" commentId="809135" commentParentId="809132"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809135" href="?#comment-809135" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809135" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809135"> <div class="moveup"> <div class="ttypography"><p>We are sorting values only once so as to connect neighboring nodes with minimum values,i.e. difference b/w consecutive values.<br /> From this sum of positive edges will be minimum.</p></div> </div> </div> <div class="reply info"> <a class="comment-809135 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809135 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809135"> <li> <div class="comment"> <table class="comment-table" commentId="809139" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809139" href="?#comment-809139" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809139" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809139"> <div class="moveup"> <div class="ttypography"><p>ohhh thanks I got it</p></div> </div> </div> <div class="reply info"> <a class="comment-809139 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809139 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809139"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809145" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809145" href="?#comment-809145" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809145" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809145"> <div class="moveup"> <div class="ttypography"><p>My solution is working now I only needed to sort the array my code would have been accepted during the contest :(</p></div> </div> </div> <div class="reply info"> <a class="comment-809145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809145"> </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="809116" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ken_KaNeKi_997" style="position: relative;"> <img src='https://userpic.codeforces.org/1737228/avatar/50ceb845253df5d4.jpg'/> </a> <div><a href="/profile/Ken_KaNeKi_997" title="Newbie Ken_KaNeKi_997" class="rated-user user-gray">Ken_KaNeKi_997</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809116" href="?#comment-809116" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809116" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1737228" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809116"> <div class="moveup"> <div class="ttypography"><p>can anyone explain div2 B plz</p></div> </div> </div> <div class="reply info"> <a class="comment-809116 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809116 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809116"> <li> <div class="comment"> <table class="comment-table" commentId="809204" commentParentId="809116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809204" href="?#comment-809204" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809116" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809204" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809204"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/92199#comment-809178">here</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809204 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809204 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809204"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809122" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809122" href="?#comment-809122" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809122" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809122"> <div class="moveup"> <div class="ttypography"><p>Beautiful Problems. Amazing Round!!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-809122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809122"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809156" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dummybawa" style="position: relative;"> <img src='https://userpic.codeforces.org/1704408/avatar/1522f670cd21321.jpg'/> </a> <div><a href="/profile/dummybawa" title="Expert dummybawa" class="rated-user user-blue">dummybawa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809156" href="?#comment-809156" style="font-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="809156" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809156" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1704408" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809156"> <div class="moveup"> <div class="ttypography"><p>UPD: It's wrong. </p></div> </div> </div> <div class="reply info"> <a class="comment-809156 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809156 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809156"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809178" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809178" href="?#comment-809178" style="font-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="809178" 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="809178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809178"> <div class="moveup"> <div class="ttypography"><p>For DIV 2C/1A can anyone explain with this test case N = 6 and D = 0 1 2 3 2 3. What are the edges that we can have with their weights?</p></div> </div> </div> <div class="reply info"> <a class="comment-809178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809178"> <li> <div class="comment"> <table class="comment-table" commentId="809198" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Zemrith" style="position: relative;"> <img src='https://userpic.codeforces.org/1159882/avatar/2a6566e372882267.jpg'/> </a> <div><a href="/profile/Zemrith" title="Expert Zemrith" class="rated-user user-blue">Zemrith</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809198" href="?#comment-809198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-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="809198" 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="809198" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159882" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809198"> <div class="moveup"> <div class="ttypography"><p>Hello! The answer would be -18.</p><p>Diagram: <img alt=" " src="/predownloaded/8c/88/8c88a0230dea9f499896ee59def659611c605976.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Notice that once you sort the distances, the adjacent nodes have no effect on your final answer. But you can add negative edges as long as they are not adjacent, resulting in such a diagram. Hence you can use prefix sums to solve the problem. (if x nodes came before this, for each node, the answer to add is (x-1)*curr value — csum of first (x-1) nodes). </p><p>Hope that made sense!</p></div> </div> </div> <div class="reply info"> <a class="comment-809198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809198"> <li> <div class="comment"> <table class="comment-table" commentId="809218" commentParentId="809198"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:27">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809218" href="?#comment-809218" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809218" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809218"> <div class="moveup"> <div class="ttypography"><p>Thank you <a class="rated-user user-cyan" href="/profile/Zemrith" title="Специалист Zemrith">Zemrith</a> for so much detail explanation and the solution too it helped me a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-809218 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809218 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809218"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809199" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809199" href="?#comment-809199" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809199" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809199"> <div class="moveup"> <div class="ttypography"><p>first sort the array they will from non negative weight edges. 0 -&gt; 1 -&gt; 2 -&gt; 2 -&gt; 3 -&gt; 3 so the non negative weights will be 1 | 1 | 0 | 1 | 0. form here greedily build most negative weights(backward edges) such that there are no negative cycles.</p></div> </div> </div> <div class="reply info"> <a class="comment-809199 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809199 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809199"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809203" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809203" href="?#comment-809203" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809203" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809203"> <div class="moveup"> <div class="ttypography"><p>First you can sort D and get: <code> N = 6, D = [0, 1, 2, 2, 3, 3] </code></p><p>Now calculate the diffs:</p><p><code>diffs = [1, 1, 0, 1, 0]</code></p><p>The edges for this graph could be something like this:</p> <pre><code> 1 1 0 1 0 &lt;- forward edges 1 &lt;-&gt; 2 &lt;-&gt; 3 &lt;-&gt; 4 &lt;-&gt; 5 &lt;-&gt; 6 -1 -1 0 -1 0 &lt;- backward edges </code></pre><p>Now you have to add more negatives edges, and you could do this by choosing some <code>i</code> and <code>j</code>, <code>i &lt; j</code> and add an edges from <code>j</code> to <code>i</code>, and the weight will be sum of the values from <code>diff[i]</code> to <code>diff[j]</code>.</p><p>Another way to think about this is: look at <code>D</code> array, it represents distances between adjacent nodes, all we have to do is add all of the edges with length 2, then all of the edges of length 3, ..., all of the edges of length <code>N - 1</code>.</p><p>So, for our case we would have these edges</p> <pre><code>a b W ------- 1 2 - 1 2 3 - 1 3 4 - 0 &lt;- adjacent forward edges 4 5 - 1 5 6 - 0 2 1 - -1 3 2 - -1 4 3 - 0 &lt;- adjacent backward edges 5 4 - -1 6 5 - 0 3 1 - -2 4 2 - -1 5 3 - -1 &lt;- edges of length 2 6 4 - -1 4 1 - -2 5 2 - -2 &lt;- edges of length 3 6 3 - -1 5 1 - -3 6 2 - -2 &lt;- edges of length 4 6 1 - -3 &lt;- edges of length 5 </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809203 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809203 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809203"> <li> <div class="comment"> <table class="comment-table" commentId="809221" commentParentId="809203"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809221" href="?#comment-809221" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809203" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809221" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809221"> <div class="moveup"> <div class="ttypography"><p>Thank You <a class="rated-user user-green" href="/profile/ilidar" title="Ученик ilidar">ilidar</a> for clearing my doubt and for detailed explaination.</p></div> </div> </div> <div class="reply info"> <a class="comment-809221 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809221 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809221"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809280" href="?#comment-809280" style="font-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="809280" revisionCount="7" revision="7"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">7</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809280" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+18</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809280"> <div class="moveup"> <div class="ttypography"><p>Could someone please provide a more strict intuition or insight of Div2D/Div1B of why &quot;the actual probability p does not matter&quot;? The intuition in the editorial is still alien to me of why those choices of not progess toward to either stacks (and probability 'p' also changes from time to time too) doesn't matter.</p><p>Update: Here is the intuition I came up with (The strict proof can be found in the comment of the author below)</p><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left) in some states of the current tree.</p><p>now, we will try break this $$$dp_{i,j}$$$ down into the sum of $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$</p><p>We will try to illustrate this with trying to split and color, either red or blue, a stick of length $$$1$$$. The length of the sticks representing the 'probability', and the color of the sticks will represent $$$dp_{i-1,j}$$$(red) or $$$dp_{i,j-1}$$$(blue), depending on the color.</p><p>Suppose in the current state, we have probability $$$p$$$ for choosing to pop each stacks, and the rest $$$1-2p$$$ of doing nothing. The picture will look like this:</p><p><a href="https://ibb.co/q9HjQTm"><img alt="Tree-Array-Rep" border="0" src="/predownloaded/13/57/135732d2b0967af0f76c1dba28df72086f234c7d.png" style="max-width: 100.0%;max-height: 100.0%;" /></a></p><p>We will split the stick equally(*) into several sticks of length $$$p$$$, and then color two of them red and blue. (* We can split it evenly because in the original problem, $$$p$$$ is in the form $$$\frac{1}{number\ of\ candidate\ unmark\ nodes}$$$ ) Now, the remaining sticks represent the state of $$$dp_{i,j}$$$ again (in some other state of the entire tree, so might be in some different $$$p$$$). That means we will split those sticks similary.</p><p>The key observations is:</p><p>1) We know that, in the original problem, if we keep picking nodes that aren't progressing toward the target nodes, we will run out of nodes eventually and finally choose the two nodes. That means, all the sticks will eventually colored into 'red' and 'blue'.</p><p>2) When we split a stick into several smaller equal length sticks, we will color two of them into red and blue. <strong>Those two sticks always have the same length</strong>. That means, the total length of blue sticks and the total length of red sticks will be equal in the end.</p><p>Analogically, that means, eventually, $$$dp_{i,j}$$$ will split into $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$ evenly, no matter $$$p$$$ might be or the state of tree of $$$dp_{i,j}$$$ might be. Therefore, $$$dp_{i,j} = \frac{1}{2} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-809280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809280"> <li> <div class="comment"> <table class="comment-table" commentId="809284" commentParentId="809280"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809284" href="?#comment-809284" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809280" style="font-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="809284" 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="809284" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809284"> <div class="moveup"> <div class="ttypography"><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left), with having arbitary probability $$$0 &lt; p \leq 0.5$$$ of chosing to pick the top of each stack (and $$$1-2p$$$ for doing nothing). Then</p><p>$$$dp_{i,j}=\int_{0}^{0.5} x \cdot (dp_{i-1,j}+dp_{i,j-1}) + (1-2x) \cdot dp_{i,j} \,dx$$$</p><p>Solving the equation, we get $$$dp_{i,j}=\frac{1}{6} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$ What is the mistake in this logic?</p></div> </div> </div> <div class="reply info"> <a class="comment-809284 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809284 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809284"> <li> <div class="comment"> <table class="comment-table" commentId="809399" commentParentId="809284"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809399" href="?#comment-809399" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809284" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809399" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809399"> <div class="moveup"> <div class="ttypography"><p>The biggest issue with this logic is that it's assuming $$$p$$$ is arbitrary chosen from a certain state. While $$$p$$$ can be anything in the world, it is always an exact number from a certain state, hence why an integral is wrong. </p><p>As a different type of intuition, you can think, &quot;is it more likely to reach $$$(i-1, j)$$$ than state $$$(i, j-1)$$$&quot;? and vice versa. For me at least, I don't see how it's possible for either of those questions to be true, so they should be equal.</p><p>If you're looking for a more rigorously correct $$$dp$$$, it would look something like this.</p> <div class="spoiler"><b class="spoiler-title">Proof</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp_{i, j, S}$$$ denote the probability of reaching some node $$$i$$$ distance away before some node $$$j$$$ distance away where $$$S$$$ is a representation of the entire state of of the process (not necessarily an integer). I think you already understood why we can assume the $$$lca$$$ is already reached. We aim to show that $$$S$$$ does not matter in our calculation. Assume inductively that $$$S$$$ does not matter. So, we can assume that states $$$(i-1, j)$$$ and states $$$(i, j-1)$$$ are irrelevant to $$$S$$$. Hence, the part we need to care about is $$$(1-2p) dp_{i, j, S \rightarrow S_a}$$$. A way of thinking about this part of the transition is moving through the collection of $$$S$$$ with the state $$$(i, j)$$$. Obviously, the $$$dp$$$ is a $$$DAG$$$ because no state $$$S$$$ can reach another. Each bounce takes a certain probability $$$p$$$ which is just multiplied in the current path. So, for each state $$$S$$$ with state $$$(i, j)$$$, we have a certain probability to reach it by simply calculating $$$dp$$$ along a DAG as is traditional. Then, from those states of $$$(i, j)$$$ you transition to $$$(i, j-1)$$$ with an equal probability $$$(i-1, j)$$$. So, they have to be equal. Finally, this argument holds for any initial state $$$S$$$ that you reach, so we can conclude that, from any state $$$S$$$ with a state of $$$(i, j)$$$, the probability of transitions to $$$(i-1, j)$$$ and $$$(i, j-1)$$$ are always exactly $$$0.5$$$.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-809399 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809399 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809399"> <li> <div class="comment"> <table class="comment-table" commentId="809701" commentParentId="809399"> <tr> <td class="left"> <div style="position: absolute; left: 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/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809701" href="?#comment-809701" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809399" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809701" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809701"> <div class="moveup"> <div class="ttypography"><p>I see, thank you so much!</p></div> </div> </div> <div class="reply info"> <a class="comment-809701 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809701 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809701"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809298" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/satyam_singh93" style="position: relative;"> <img src='https://userpic.codeforces.org/1763011/avatar/9d9fa405de19ab0e.jpg'/> </a> <div><a href="/profile/satyam_singh93" title="Newbie satyam_singh93" class="rated-user user-gray">satyam_singh93</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809298" href="?#comment-809298" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809298" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1763011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809298"> <div class="moveup"> <div class="ttypography"><p>I am getting wrong ans . could someone tell me where the code make differene ( [yestrday competiton problem .</p><p>`](<a href="https://codeforces.com/contest/1541/problem/B)">https://codeforces.com/contest/1541/problem/B)</a>.</p> <pre><code>int main( ) { clock_t begin = clock(); file_i_o(); // Write your code here.... int t; cin&gt;&gt;t; while(t-- ){ int n; cin&gt;&gt;n; vector&lt;pair&lt;int,int&gt;&gt;v; v.push_back({0,0}); loop(i,0,n) { int x; cin&gt;&gt;x; v.pb({x,i+1}); } sort(v.begin()+1,v.end()); int count =0; for(int i=1 ; i&lt;=n;i++) { for(ll j=i+1;j&lt;=n;j++) { ll left = v[i].first * v[j].first; ll right = v[i].second + v[j].second; if(left == right) count++; if(left &gt; 2*n ) break; } } cout&lt;&lt;count&lt;&lt;endl; } </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809298 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809298 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809298"> <li> <div class="comment"> <table class="comment-table" commentId="809305" commentParentId="809298"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809305" href="?#comment-809305" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809298" style="font-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="809305" 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="809305" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809305"> <div class="moveup"> <div class="ttypography"><p>v[i].first * v[j].first can create overflow. So, you need to convert them to long long by using</p><p>ll left = 1LL * v[i].first * v[j].first;</p><p>instead and it would pass.</p><p>(Simply save the value in long long won't help. You need to convert them to long long before doing multiplication. 1LL* is one way)</p></div> </div> </div> <div class="reply info"> <a class="comment-809305 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809305 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809305"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809309" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809309" href="?#comment-809309" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809309" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809309"> <div class="moveup"> <div class="ttypography"><p>Hi, in problem Div1.B/Div2.D; I can't wrap my head around $$$F[x][y]=F[x−1][y]/2+F[x][y−1]/2$$$. Why is it not $$$F[x][y]=F[x−1][y+1]/2+F[x+1][y−1]/2$$$, can someone please explain to me why is my transition wrong and/or why is the aforementioned transition correct? </p></div> </div> </div> <div class="reply info"> <a class="comment-809309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809309"> <li> <div class="comment"> <table class="comment-table" commentId="809311" commentParentId="809309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809311" href="?#comment-809311" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809311" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809311"> <div class="moveup"> <div class="ttypography"><p>x and y is the distance left for each side right? So, if you take one out, it won't make sense to add that one to the other side since the distance should be either x-1 and y or x and y-1.</p></div> </div> </div> <div class="reply info"> <a class="comment-809311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809311"> <li> <div class="comment"> <table class="comment-table" commentId="809339" commentParentId="809311"> <tr> <td class="left"> <div style="position: absolute; left: 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/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809339" href="?#comment-809339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809339" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809339"> <div class="moveup"> <div class="ttypography"><p>Thank you so much I understand. I had a minor misunderstanding of the parameters to the dp state.</p></div> </div> </div> <div class="reply info"> <a class="comment-809339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809339"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809371" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:13">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809371" href="?#comment-809371" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809371" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809371"> <div class="moveup"> <div class="ttypography"><p>PLease explain why 2 same codes are not giving the same ans</p><p>code forces round 728 div2<br />Problem B :<a href="https://codeforces.com/contest/1541/problem/B">https://codeforces.com/contest/1541/problem/B</a></p><p>AC Submission : <a href="https://ide.codingblocks.com/s/579769">https://ide.codingblocks.com/s/579769</a></p><p>Wrong output Submission :<a href="https://ide.codingblocks.com/s/579771">https://ide.codingblocks.com/s/579771</a></p><p>Difference is using of macro (node) instead of pair&lt;int,int&gt; </p><p>Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-809371 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809371 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809371"> <li> <div class="comment"> <table class="comment-table" commentId="809379" commentParentId="809371"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809379" href="?#comment-809379" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809371" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809379" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809379"> <div class="moveup"> <div class="ttypography"><p>If i am using #define node pair&lt;int,int&gt; it is getting accepted but when i am using typedef pair&lt;int,int&gt; node; it is giving wrong answer</p><p>Why this is happening ?? Is it a bug??</p></div> </div> </div> <div class="reply info"> <a class="comment-809379 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809379 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809379"> <li> <div class="comment"> <table class="comment-table" commentId="809407" commentParentId="809379"> <tr> <td class="left"> <div style="position: absolute; left: 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/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 19:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809407" href="?#comment-809407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809379" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809407" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809407"> <div class="moveup"> <div class="ttypography"><p>Not really sure why this is happening.</p><p>However, I think the problem is the position of #define int long long. So, for #define pair&lt;int,int&gt; node it seems that compiler change node -&gt; pair&lt;int,int&gt; -&gt; pair&lt;long long, long long&gt;. However, when you do typedef, it still keeps in pair&lt;int, int&gt; which creates an overflow problem later on. </p><p>I did try moving #define int long long up above typedef and the code pass. So, my best guess is #define int long long only replace int after that position with long long. Thus, node is still pair&lt;int, int&gt; in the typedef solution, while node is changed to pair&lt;long long, long long&gt; in the second solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-809407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809407"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809627" href="?#comment-809627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809627"> <div class="moveup"> <div class="ttypography"><p>May I ask why in the Div1D solution ci=i-bi, I think it should be ci=bi ...</p></div> </div> </div> <div class="reply info"> <a class="comment-809627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809627"> <li> <div class="comment"> <table class="comment-table" commentId="809631" commentParentId="809627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809631" href="?#comment-809631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809631" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809631"> <div class="moveup"> <div class="ttypography"><p>Check the definition of bi again dude. bi here means <strong>number of elements greater than pi</strong>. So to get ci, which is <strong>number of elements smaller than pi</strong>, you need i-bi.</p></div> </div> </div> <div class="reply info"> <a class="comment-809631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809631"> <li> <div class="comment"> <table class="comment-table" commentId="809636" commentParentId="809631"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809636" href="?#comment-809636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809636"> <div class="moveup"> <div class="ttypography"><p>I read it again. If I read it correctly, bi stands for j&lt;i,pj&gt;pi, and ci stands for j&gt;i,pj&lt;pi. For example, p={1,3,5,4,6,2}, I think b4=1,c4=1, please point out my problem</p></div> </div> </div> <div class="reply info"> <a class="comment-809636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809636"> <li> <div class="comment"> <table class="comment-table" commentId="809638" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809638" href="?#comment-809638" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809638" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809638"> <div class="moveup"> <div class="ttypography"><p>oh, the array index starts from 1</p></div> </div> </div> <div class="reply info"> <a class="comment-809638 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809638 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809638"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809639" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809639" href="?#comment-809639" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809639" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809639"> <div class="moveup"> <div class="ttypography"><p>You are right.</p><p>I guess it might just be typo and ci stands for j&lt;i, pj&lt;pi. At least with this definition of ci the algorithm seems correct :)</p></div> </div> </div> <div class="reply info"> <a class="comment-809639 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809639 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809639"> <li> <div class="comment"> <table class="comment-table" commentId="809641" commentParentId="809639"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809641" href="?#comment-809641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809639" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809641"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-809641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809641"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809705" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/darthrevenge" style="position: relative;"> <img src='https://userpic.codeforces.org/1567000/avatar/ee31d2a91a9575b9.jpg'/> </a> <div><a href="/profile/darthrevenge" title="Candidate Master darthrevenge" class="rated-user user-violet">darthrevenge</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809705" href="?#comment-809705" style="font-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="809705" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809705" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1567000" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809705"> <div class="moveup"> <div class="ttypography"><p>Here's my solution of B div 1 / D div 2 without LCA, using single DFS per node. <a href="/contest/1540/submission/120700765" title="Посылка 120700765 от darthrevenge">120700765</a> It is similar to what <a class="rated-user user-violet" href="/profile/OleschY" title="Кандидат в мастера OleschY">OleschY</a> suggested above. I've tried to describe it in the <a href="https://codeforces.com/blog/entry/92284">blog</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-809705 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809705 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809705"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809951" href="?#comment-809951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809951"> <div class="moveup"> <div class="ttypography"><p>Can someone explain how you can find the LCA for each pair so quick? Iterating through every root is and then considering every pair is already N^3</p></div> </div> </div> <div class="reply info"> <a class="comment-809951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809951"> <li> <div class="comment"> <table class="comment-table" commentId="809965" commentParentId="809951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PurpleCrayon" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809965" href="?#comment-809965" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809965" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="1604355" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809965"> <div class="moveup"> <div class="ttypography"><p>There are a couple ways you could do it:</p> <ol> <li>Just use standard binary lifting (initialize once for each root). This runs in $$$\mathcal{O}(n^3 \log{}n)$$$, and should pass under the given constraints. You could also just use $$$\mathcal{O}(1)$$$ lca using an rmq over an euler tour.</li> <li>You could use a version of dp, where $$$dp[a][b] = lca(a, b)$$$. If the depth of $$$a$$$ is greater than the depth of $$$b$$$, $$$dp[a][b] = dp[parent[a]][b]$$$, otherwise $$$dp[a][b] = dp[a][parent[b]]$$$. The base cases are $$$dp[a][a] = a$$$ for all $$$a$$$. This runs in $$$\mathcal{O}(n^3)$$$.</li> <li>You could extend this idea and do the main solution's dp directly on the tree (without ever worrying about lca's). The recurrence is equivalent to the main solution ($$$dp[a][b] = \frac{dp[parent[a]][b]+dp[a][parent[b]]}{2}$$$ with the base cases being one node is an ancestor of the other.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-809965 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809965 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809965"> <li> <div class="comment"> <table class="comment-table" commentId="809967" commentParentId="809965"> <tr> <td class="left"> <div style="position: absolute; left: 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/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809967" href="?#comment-809967" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809965" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809967" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809967"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the detailed answer!</p></div> </div> </div> <div class="reply info"> <a class="comment-809967 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809967 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809967"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="810320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Anurag_20" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Anurag_20" title="Specialist Anurag_20" class="rated-user user-cyan">Anurag_20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/30/2021 19:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810320" href="?#comment-810320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810320" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1600346" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810320"> <div class="moveup"> <div class="ttypography"><p>O(n2) is also working for div2 C Great Graphs. <a href="https://codeforces.com/contest/1540/submission/120964787">https://codeforces.com/contest/1540/submission/120964787</a></p></div> </div> </div> <div class="reply info"> <a class="comment-810320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810320"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="813828" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/T404" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/T404" title="Master T404" class="rated-user user-orange">T404</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/09/2021 19:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-813828" href="?#comment-813828" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="813828" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="523287" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-813828"> <div class="moveup"> <div class="ttypography"><p>Div1D can be done in $$$O(n \sqrt{n})$$$. We can use square root decomposition to replace all BITs in tutorial. Since a value in a non-updated position changes by at most one and all values change in the same direction, the full recomputation is only needed in the updated position and we can perform an incremental change in $$$O(1)$$$ for values in each non-updated positions.</p><p><a href="https://codeforces.com/contest/1540/submission/121831547">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-813828 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-813828 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-813828"> <li> <div class="comment"> <table class="comment-table" commentId="834051" commentParentId="813828"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KeyID" style="position: relative;"> <img src='https://userpic.codeforces.org/226684/avatar/10e3671716bf6859.jpg'/> </a> <div><a href="/profile/KeyID" title="Grandmaster KeyID" class="rated-user user-red">KeyID</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/29/2021 12:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-834051" href="?#comment-834051" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-813828" style="font-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="834051" 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="834051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="226684" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-834051"> <div class="moveup"> <div class="ttypography"><p>Realy impressive solution. I'm surprised no stars were given to you until me. Maybe many people didn't get your idea since the solution is actually much more complicated than your brief comment(at least in my opinion). I also wrote a piece of code which used your method but simplified a small part of steps. <a href="https://codeforces.com/contest/1540/submission/127317031">Here</a> it is.</p></div> </div> </div> <div class="reply info"> <a class="comment-834051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-834051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-834051"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="837924" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Harolinch" style="position: relative;"> <img src='https://userpic.codeforces.org/427341/avatar/cf8608aeb55edc95.jpg'/> </a> <div><a href="/profile/Harolinch" title="Pupil Harolinch" class="rated-user user-green">Harolinch</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837924" href="?#comment-837924" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837924" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="427341" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837924"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a> in problem Tree array you said that Fixing a given root r, the expected value of the entire process is obviously the sum of the expected values for a fixed root divided by n.</p><p>why we divide by n at the end ? </p></div> </div> </div> <div class="reply info"> <a class="comment-837924 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837924 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837924"> <li> <div class="comment"> <table class="comment-table" commentId="837928" commentParentId="837924"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837928" href="?#comment-837928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-837924" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837928" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837928"> <div class="moveup"> <div class="ttypography"><p>The calculation is independent based on whichever node that you choose first (it becomes the “root”). Initially you choose one of $$$n$$$ nodes with equal probability so you divide by $$$n$$$ at the end after you’ve summed up the independent expected value after choosing the node $$$i$$$ initially.</p></div> </div> </div> <div class="reply info"> <a class="comment-837928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837928"> </ul> </div> </li> </ul> </div> <br/> <div id="editBox-100805" 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 firstPreview100805 = true; var lastPreviewContent100805 = ''; 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=100805] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=100805] 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-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, 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:33:28</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:'81289372dffb0c4e',t:'MTY5NjcwNzIwOC45MzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1541E1
1541
E1
ru
E1. Сходящийся массив (простая версия)
<div class="problem-statement"><div class="header"><div class="title">E1. Сходящийся массив (простая версия)</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-bf">Это — упрощенная версия задачи. Единственное различие в том, что в данной версии $$$q = 1$$$. Вы можете взламывать другие решения, только если решены обе версии задачи.</span></p><p>Рассмотрим процесс, проходящий на массивах $$$a$$$ и $$$b$$$ длины $$$n$$$ и $$$n-1$$$ соответственно. </p><p>Процесс — это бесконечная последовательность действий. Каждое действие имеет следующий вид: </p><ul> <li> Сначала выберем случайное целое число $$$i$$$ ($$$1 \le i \le n-1$$$). </li><li> Теперь одновременно присвоим $$$a_i = \min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right)$$$ и $$$a_{i+1} = \max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right)$$$ без округлений (то есть значения могут перестать быть целыми). </li></ul> Пример такой операции представлен в заметках.<p>Можно доказать, что массив $$$a$$$ сходится, т. е. для каждого $$$i$$$ существует предел, к которому $$$a_i$$$ сходится. Пусть функция $$$F(a, b)$$$ возвращает значение, к которому сходится $$$a_1$$$, в результате процесса на массивах $$$a$$$ и $$$b$$$.</p><p>Вам задан массив $$$b$$$, но не массив $$$a$$$. Однако вам задан третий массив $$$c$$$. Назовем массив $$$a$$$ хорошим, если он состоит из <span class="tex-font-style-bf">целых чисел</span> и удовлетворяет неравенству $$$0 \leq a_i \leq c_i$$$ для всех $$$1 \leq i \leq n$$$.</p><p>Ваша задача — посчитать количество хороших массивов $$$a$$$, для которых $$$F(a, b) \geq x$$$, для $$$q$$$ значений $$$x$$$. Так как ответ может быть слишком большим, выведите его по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$2 \le n \le 100$$$).</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$c_1, c_2 \ldots, c_n$$$ ($$$0 \le c_i \le 100$$$).</p><p>В третьей строке заданы $$$n-1$$$ целых чисел $$$b_1, b_2, \ldots, b_{n-1}$$$ ($$$0 \le b_i \le 100$$$).</p><p>В четвертой строке задано одно целое число $$$q$$$ ($$$q=1$$$).</p><p>В пятой строке заданы $$$q$$$ целых чисел $$$x_1, x_2, \ldots, x_q$$$ ($$$-10^5 \le x_i \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ целых чисел, где $$$i$$$-е число — ответ на $$$i$$$-й запрос, т. е. количество хороших массивов $$$a$$$ с $$$F(a, b) \geq x_i$$$ по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 3 4 2 1 1 -1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 56 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Объяснение далее предполагает, что $$$b = [2, 1]$$$ и $$$c=[2, 3, 4]$$$ (как в примере).</p><p>Примеры массивов $$$a$$$, которые <span class="tex-font-style-bf">не</span> являются хорошими: </p><ul> <li> $$$a = [3, 2, 3]$$$ не является хорошим, потому что $$$a_1 &gt; c_1$$$; </li><li> $$$a = [0, -1, 3]$$$ не является хорошим, потому что $$$a_2 &lt; 0$$$. </li></ul><p>Один из возможных хороших массивов $$$a$$$ — это $$$[0, 2, 4]$$$. Можно показать, что ни одна операция его не изменит, а потому $$$F(a, b) = a_1 = 0$$$.</p><p>Другой возможных хороший массив $$$a$$$ — это $$$[0, 1, 4]$$$. За одну операцию с $$$i = 1$$$ мы присваиваем $$$a_1 = \min(\frac{0+1-2}{2}, 0)$$$ и $$$a_2 = \max(\frac{0+1+2}{2}, 1)$$$. То есть, после одной операции с $$$i = 1$$$, $$$a$$$ становится равен $$$[-\frac{1}{2}, \frac{3}{2}, 4]$$$. Можно показать, что далее ни одна операция не изменит массив, а потому $$$F(a, b) = -\frac{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="0fa343d0fc53472471cf0456ec286c29"/> <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="3a2e30eec6604291efb1f3ef212d19e2d7715bd7"/> <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='0fa343d0fc53472471cf0456ec286c29'>&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%2F1541%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='0fa343d0fc53472471cf0456ec286c29'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1541">Codeforces Round 728 (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='0fa343d0fc53472471cf0456ec286c29'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1541/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='0fa343d0fc53472471cf0456ec286c29'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1027096"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0fa343d0fc53472471cf0456ec286c29'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1027096"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92093" title="Codeforces Round #728" target="_blank">Codeforces Round #728 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13929" resourceName="Codeforces Round #728" resourceManual="true" src="//codeforces.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/92199" title="Tutorial" target="_blank">Tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13941" 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/1541">Задачи</a></li> <li><a href="/contest/1541/submit">Отослать</a></li> <li><a href="/contest/1541/my">Мои посылки</a></li> <li><a href="/contest/1541/status">Статус</a></li> <li><a href="/contest/1541/hacks">Взломы</a></li> <li><a href="/contest/1541/room/1">Комната</a></li> <li><a href="/contest/1541/standings">Положение</a></li> <li><a href="/contest/1541/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0ee6292e0d49ae55abb6a1dac4c873c8222f20d9"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это — упрощенная версия задачи. Единственное различие в том, что в данной версии $$$q = 1$$$. Вы можете взламывать другие решения, только если решены обе версии задачи.</span></p><p>Рассмотрим процесс, проходящий на массивах $$$a$$$ и $$$b$$$ длины $$$n$$$ и $$$n-1$$$ соответственно. </p><p>Процесс — это бесконечная последовательность действий. Каждое действие имеет следующий вид: </p><ul> <li> Сначала выберем случайное целое число $$$i$$$ ($$$1 \le i \le n-1$$$). </li><li> Теперь одновременно присвоим $$$a_i = \min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right)$$$ и $$$a_{i+1} = \max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right)$$$ без округлений (то есть значения могут перестать быть целыми). </li></ul> Пример такой операции представлен в заметках.<p>Можно доказать, что массив $$$a$$$ сходится, т. е. для каждого $$$i$$$ существует предел, к которому $$$a_i$$$ сходится. Пусть функция $$$F(a, b)$$$ возвращает значение, к которому сходится $$$a_1$$$, в результате процесса на массивах $$$a$$$ и $$$b$$$.</p><p>Вам задан массив $$$b$$$, но не массив $$$a$$$. Однако вам задан третий массив $$$c$$$. Назовем массив $$$a$$$ хорошим, если он состоит из <span class="tex-font-style-bf">целых чисел</span> и удовлетворяет неравенству $$$0 \leq a_i \leq c_i$$$ для всех $$$1 \leq i \leq n$$$.</p><p>Ваша задача — посчитать количество хороших массивов $$$a$$$, для которых $$$F(a, b) \geq x$$$, для $$$q$$$ значений $$$x$$$. Так как ответ может быть слишком большим, выведите его по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$2 \le n \le 100$$$).</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$c_1, c_2 \ldots, c_n$$$ ($$$0 \le c_i \le 100$$$).</p><p>В третьей строке заданы $$$n-1$$$ целых чисел $$$b_1, b_2, \ldots, b_{n-1}$$$ ($$$0 \le b_i \le 100$$$).</p><p>В четвертой строке задано одно целое число $$$q$$$ ($$$q=1$$$).</p><p>В пятой строке заданы $$$q$$$ целых чисел $$$x_1, x_2, \ldots, x_q$$$ ($$$-10^5 \le x_i \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ целых чисел, где $$$i$$$-е число — ответ на $$$i$$$-й запрос, т. е. количество хороших массивов $$$a$$$ с $$$F(a, b) \geq x_i$$$ по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 3 4 2 1 1 -1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 56 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Объяснение далее предполагает, что $$$b = [2, 1]$$$ и $$$c=[2, 3, 4]$$$ (как в примере).</p><p>Примеры массивов $$$a$$$, которые <span class="tex-font-style-bf">не</span> являются хорошими: </p><ul> <li> $$$a = [3, 2, 3]$$$ не является хорошим, потому что $$$a_1 &gt; c_1$$$; </li><li> $$$a = [0, -1, 3]$$$ не является хорошим, потому что $$$a_2 &lt; 0$$$. </li></ul><p>Один из возможных хороших массивов $$$a$$$ — это $$$[0, 2, 4]$$$. Можно показать, что ни одна операция его не изменит, а потому $$$F(a, b) = a_1 = 0$$$.</p><p>Другой возможных хороший массив $$$a$$$ — это $$$[0, 1, 4]$$$. За одну операцию с $$$i = 1$$$ мы присваиваем $$$a_1 = \min(\frac{0+1-2}{2}, 0)$$$ и $$$a_2 = \max(\frac{0+1+2}{2}, 1)$$$. То есть, после одной операции с $$$i = 1$$$, $$$a$$$ становится равен $$$[-\frac{1}{2}, \frac{3}{2}, 4]$$$. Можно показать, что далее ни одна операция не изменит массив, а потому $$$F(a, b) = -\frac{1}{2}$$$.</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 11:29: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:'8124c713e85f7b83',t:'MTY5NjY2NzM3OS44ODEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*2700"]
https://codeforces.com/blog/entry/92199
<!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="ea33d124a1ff874ace73f937748d303e"/> <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="Codeforces Round #728 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #728 Editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='ea33d124a1ff874ace73f937748d303e'>&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%2F92199">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='ea33d124a1ff874ace73f937748d303e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:31:32</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:31:32</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='ea33d124a1ff874ace73f937748d303e'/> <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/PurpleCrayon">PurpleCrayon</a></li> <li class="current selectedLava"><a href="/blog/PurpleCrayon">Blog</a></li> <li><a href="/teams/with/PurpleCrayon">Teams</a></li> <li><a href="/submissions/PurpleCrayon">Submissions</a></li> <li><a href="/groups/with/PurpleCrayon">Groups</a></li> <li><a href="/contests/with/PurpleCrayon">Contests</a></li> <li><a href="/contests/writer/PurpleCrayon">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/PurpleCrayon" style="text-decoration:none;color:black !important;">PurpleCrayon's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="92809"> <div class="title"> <a href="/blog/entry/92199"> <p>Codeforces Round #728 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a>, <a href="/topic/92809/en10">history</a>, <span class="format-humantime" title="Jun/25/2021 20:44">2 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><a href="/contest/1541/problem/A" title="Codeforces Round 728 (Div. 2)">1541A - Pretty Permutations</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The parity (whether $$$n$$$ is odd or even) matters.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Swapping two adjacent cats keeps both of them close to their original location and changes both of their locations.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>If $$$n$$$ is even, the optimal distance is $$$n$$$, and if $$$n$$$ is odd the optimal distance is $$$n+1$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541A">Tutorial is loading...</div></div></div><p><a href="/contest/1541/problem/B" title="Codeforces Round 728 (Div. 2)">1541B - Pleasant Pairs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>$$$i+j \leq 2 \cdot n$$$</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The number of pairs $$$(a, b)$$$ such that $$$a \cdot b \leq x$$$ is $$$O(x log x)$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/A" title="Codeforces Round 728 (Div. 1)">1540A - Great Graphs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What's the minimum value that an edge from $$$a$$$ to $$$b$$$ can be?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use edges with negative value whenever you can.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The sum of the values of edges with positive weight must be $$$\geq$$$ the maximum value in the array.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540A">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Tree Array</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Fix the initial node chosen and root the tree there, what is the contribution of each pair of nodes?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Nothing matters besides the path from node $$$a$$$ to node $$$b$$$, and the initially chosen node $$$r$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>You are given two stacks of size $$$a_1$$$ and $$$a_2$$$. In a single step, you randomly choose a stack to remove a single item from. What is the probability that $$$a_1$$$ becomes $$$0$$$ before $$$a_2$$$? Can you extend this argument for an arbitrary probability $$$p$$$ to remove from one of the two stacks, and a probability of $$$1-2p$$$ to do nothing?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/C2" title="Codeforces Round 728 (Div. 1)">1540C2 - Converging Array (Hard Version)</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What are the invariants? The monovariants?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What is the prefix sum array of the converged array? What is the difference array of the converged array?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you conducted the process on a prefix of size $$$1$$$, then of size $$$2$$$, and on and on?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How many values $$$x$$$ are actually interesting?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540C2">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Inverse Inversions</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The answer is always unique.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Try to figure out what the location of the $$$i$$$-th element would be if you only looked at the first $$$i$$$ elements, then the first $$$i+1$$$, etc. to find an $$$O(nq)$$$ solution.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use sqrt decomposition to optimize it.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540D">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/E" title="Codeforces Round 728 (Div. 1)">1540E - Tasty Dishes</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How much does each chef's initial dish contribute at time $$$k$$$?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you really, really wanted to use matrix exponentiation?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How can you multiply some vectors by a matrix in $$$O(N)$$$ time? (go back to linear algebra class)</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Decompose into linear combinations of eigenvectors.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540E">Tutorial is loading...</div></div></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/1540" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 1)</a> </span> </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/1541" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-191295-92809").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "191295", blogEntryId: "92199", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-92809"><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'>+96</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-92809"><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/PurpleCrayon"><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/PurpleCrayon"> PurpleCrayon </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="Jun/25/2021 20:44">2 years ago</span> </li> <li> <a href="/blog/entry/92199#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/92199#comments"> 170 </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="100805"> <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 (136)</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="808750" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808750" href="?#comment-808750" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808750" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-66" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-66</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808750"> <div class="moveup"> <div class="ttypography"><p>PURPLECRAYON ORZ</p></div> </div> </div> <div class="reply info"> <a class="comment-808750 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808750 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808750"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808751" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hbarp" style="position: relative;"> <img src='https://userpic.codeforces.org/1387715/avatar/c727a810db6ffb66.jpg'/> </a> <div><a href="/profile/hbarp" title="Candidate Master hbarp" class="rated-user user-violet">hbarp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808751" href="?#comment-808751" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808751" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="1387715" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-83</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808751"> <div class="moveup"> <div class="ttypography"><p>Damn, so orz round. <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Мастер PurpleCrayon">PurpleCrayon</a> orz</p></div> </div> </div> <div class="reply info"> <a class="comment-808751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808751"> <li> <div class="comment"> <table class="comment-table" commentId="808805" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/naman1601" style="position: relative;"> <img src='https://userpic.codeforces.org/1703219/avatar/d63fc523dc05fda8.jpg'/> </a> <div><a href="/profile/naman1601" title="Master naman1601" class="rated-user user-orange">naman1601</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808805" href="?#comment-808805" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808805" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-51" data-commentUserId="1703219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-51</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808805"> <div class="moveup"> <div class="ttypography"><p>yeah, amazing problemset, not speedforces at all :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808805 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808805 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808805"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808817" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LOVELY_BOY_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/LOVELY_BOY_" title="Newbie LOVELY_BOY_" class="rated-user user-gray">LOVELY_BOY_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808817" href="?#comment-808817" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-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="808817" 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="808817" class="CommentVoteFrame" data-commentRating="35" data-commentUserId="2089809" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808817"> <div class="moveup"> <div class="ttypography"><p>LOL <a class="rated-user user-blue" href="/profile/hbarp" title="Эксперт hbarp">hbarp</a>,even you didn't participate in the contest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808817 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808817 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808817"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808753" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DontLookBack" style="position: relative;"> <img src='https://userpic.codeforces.org/1534766/avatar/4eacdc5f9758fc28.jpg'/> </a> <div><a href="/profile/DontLookBack" title="Specialist DontLookBack" class="rated-user user-cyan">DontLookBack</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808753" href="?#comment-808753" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808753" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1534766" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808753"> <div class="moveup"> <div class="ttypography"><p>I am curious, how many div2 testers solved D?</p></div> </div> </div> <div class="reply info"> <a class="comment-808753 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808753 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808753"> <li> <div class="comment"> <table class="comment-table" commentId="808826" commentParentId="808753"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/highonjuice" style="position: relative;"> <img src='https://userpic.codeforces.org/1457566/avatar/f7988dd2af03d38b.jpg'/> </a> <div><a href="/profile/highonjuice" title="Pupil highonjuice" class="rated-user user-green">highonjuice</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808826" href="?#comment-808826" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808753" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808826" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1457566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808826"> <div class="moveup"> <div class="ttypography"><p>like 2 ppl, it was hard for me</p></div> </div> </div> <div class="reply info"> <a class="comment-808826 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808826 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808826"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808757" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tlatoani" style="position: relative;"> <img src='https://userpic.codeforces.org/614001/avatar/598b4e8358aad1b4.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/Tlatoani" title="Grandmaster Tlatoani" class="rated-user user-red">Tlatoani</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:18">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808757" href="?#comment-808757" style="font-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="808757" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="808757" class="CommentVoteFrame" data-commentRating="121" data-commentUserId="614001" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+121</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808757"> <div class="moveup"> <div class="ttypography"><h4>Alternate solution to <a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Инвертируем инверсии</a></h4><p>(Read the first nontrivial paragraph of the editorial before reading this alternate solution)</p><p>Let $$$p_r(k) = x$$$ denote that of the numbers $$$p(1), \ldots, p(r)$$$ in sorted order, $$$p(k)$$$ is equal to the $$$x$$$th of these numbers. We will take a decomposition strategy just as the editorial does, though our strategy will be different. We will divide $$$[1, n]$$$ into blocks of length $$$b$$$. For each block covering some interval $$$[l, r]$$$, we will store $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>This means that for any $$$k$$$, if we know $$$p_r(k)$$$ for some block $$$[l, r]$$$, then we can determine $$$p_{r'}(k)$$$ for the block $$$[l', r']$$$ immediately to the right by binary searching on the numbers stored for $$$[l', r']$$$. Therefore, we can perform queries in $$$O\left(\frac n b \lg b\right)$$$.</p><p>We now need to figure out updates. There are probably simple ways to perform updates in $$$O(b\lg b)$$$, but this yields an overall runtime of $$$O(q\sqrt n \lg n)$$$ which is too slow.</p><p>Therefore, we can instead store each block as a segment tree. For each range $$$[l, r]$$$ in the segment tree we store the same thing we store for the whole block: $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>We then have to quickly merge two intervals. We can merge two intervals of length $$$\lambda$$$ in $$$O(\lambda \lg \lambda)$$$ by doing binary search just as we did above, but this still only yields $$$O(b\lg b)$$$ update overall. However, these $$$\lambda$$$ binary searches can be optimized using two pointers to $$$O(\lambda)$$$, making the overall update $$$O(b)$$$.</p><p>We thus have $$$O\left(\frac n b \lg b\right)$$$ query and $$$O(b)$$$ update. Therefore, we can choose $$$b = \sqrt{n\lg n}$$$ to attain an overall runtime of $$$O\left(q\sqrt{n\lg n}\right)$$$ just as the editorial does.</p><p><a href="https://codeforces.com/contest/1540/submission/120611645">Submission in Kotlin</a></p><p><a href="https://codeforces.com/contest/1540/submission/120612729">Submission in C++</a></p><p>It is interesting to note that this solution is quite fast. At the time of writing this update, the C++ version is the fastest correct submission (and runs under 1 second!) and the Kotlin version is faster than the vast majority of submissions.</p></div> </div> </div> <div class="reply info"> <a class="comment-808757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808757"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808765" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardcode229" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardcode229" title="Newbie hardcode229" class="rated-user user-gray">hardcode229</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808765" href="?#comment-808765" style="font-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="808765" 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="808765" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1635180" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808765"> <div class="moveup"> <div class="ttypography"><p>The 3rd hint for the second problem is same as that of the first problem, is it related or a mistake? <strong>UPD:</strong> it is corrected.</p></div> </div> </div> <div class="reply info"> <a class="comment-808765 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808765 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808765"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808769" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/peanut" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/peanut" title="Specialist peanut" class="rated-user user-cyan">peanut</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:24">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808769" href="?#comment-808769" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808769" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="1167233" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+22</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808769"> <div class="moveup"> <div class="ttypography"><p>speedforces.</p></div> </div> </div> <div class="reply info"> <a class="comment-808769 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808769 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808769"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808781" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/graphs_11" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/graphs_11" title="Specialist graphs_11" class="rated-user user-cyan">graphs_11</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808781" href="?#comment-808781" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808781" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1610110" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808781"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">Problem B Detailed Explanation</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808781 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808781 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808781"> <li> <div class="comment"> <table class="comment-table" commentId="809069" commentParentId="808781"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:40">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809069" href="?#comment-809069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808781" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809069" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809069"> <div class="moveup"> <div class="ttypography"><p>Thank you, very well explained</p></div> </div> </div> <div class="reply info"> <a class="comment-809069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809069"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808790" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PC_E1052" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PC_E1052" title="Pupil PC_E1052" class="rated-user user-green">PC_E1052</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808790" href="?#comment-808790" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808790" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="811219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808790"> <div class="moveup"> <div class="ttypography"><p>c was too easy, d was too hard. but d was very nice problem though. </p></div> </div> </div> <div class="reply info"> <a class="comment-808790 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808790 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808790"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808793" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808793" href="?#comment-808793" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808793" class="CommentVoteFrame" data-commentRating="58" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+58</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808793"> <div class="moveup"> <div class="ttypography"><p>Paging <a class="rated-user user-legendary" href="/profile/ecnerwala" title="Легендарный гроссмейстер ecnerwala"><span class="legendary-user-first-letter">e</span>cnerwala</a> to explain his solution to D1E if he'd like. It seems offline?</p></div> </div> </div> <div class="reply info"> <a class="comment-808793 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808793 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808793"> <li> <div class="comment"> <table class="comment-table" commentId="808979" commentParentId="808793"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ecnerwala" 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/ecnerwala" title="Legendary Grandmaster ecnerwala" class="rated-user user-legendary"><span class="legendary-user-first-letter">e</span>cnerwala</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808979" href="?#comment-808979" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808793" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808979" class="CommentVoteFrame" data-commentRating="40" data-commentUserId="57502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808979"> <div class="moveup"> <div class="ttypography"><p>My solution is $$$O(K N^3 + QN)$$$. I just precomputed the coefficient of each $$$a_i$$$ for each prefix-range for each number of days since person $$$i$$$ becomes positive (only $$$1000$$$ possible days) in $$$O(N \cdot K \cdot N^2)$$$, and then summed up the appropriate ones to answer each query in $$$O(N)$$$. It's written in the offline style to use only $$$O(KN)$$$ memory at a time (grouped by $$$a_i$$$) instead of $$$O(KN^2)$$$.</p><p>My passing submission is just $$$KN^3 / 6$$$ instead of the $$$KN^3$$$ I submitted in contest :'(</p><p>If you guys wanted to prevent this, $$$K$$$ could've been much higher, like $$$1e18$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808979 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808979 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808979"> <li> <div class="comment"> <table class="comment-table" commentId="809002" commentParentId="808979"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809002" href="?#comment-809002" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808979" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809002" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809002"> <div class="moveup"> <div class="ttypography"><p>:( I knew of this solution (it’s why ML is tight) but I didn’t realize that it could be done offline with small memory. Of course $$$K$$$ higher is obvious solution but main issue is that the extra modulos from binary exponentiation make it very hard to pass in Java without allowing other unoptimal solutions through such as precomputing inverses of the matrix. Probably $$$k=10^5$$$ would’ve been a better choice. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-809002 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809002 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809002"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808795" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zukonit14" style="position: relative;"> <img src='https://userpic.codeforces.org/1192187/avatar/5afd49be87fb87d9.jpg'/> </a> <div><a href="/profile/zukonit14" title="Expert zukonit14" class="rated-user user-blue">zukonit14</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808795" href="?#comment-808795" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808795" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1192187" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808795"> <div class="moveup"> <div class="ttypography"><p>Does Div2 D deserved to be D Problem? According to me it should've been Div2 E.</p></div> </div> </div> <div class="reply info"> <a class="comment-808795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808795"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808796" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mangat_angad" style="position: relative;"> <img src='https://userpic.codeforces.org/1449578/avatar/d3cadb0c26e0c11f.jpg'/> </a> <div><a href="/profile/mangat_angad" title="Specialist mangat_angad" class="rated-user user-cyan">mangat_angad</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808796" href="?#comment-808796" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808796" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1449578" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808796"> <div class="moveup"> <div class="ttypography"><p>I feel like such an idiot for not being able to understand problem C (Div2). For some reason I thought the nodes were connected like this — 1-&gt;2-&gt;3-&gt;....-&gt;N and that we had to minimise answer by adding other edges (of negative weight in case they dont give a negative cycle) to this graph.</p></div> </div> </div> <div class="reply info"> <a class="comment-808796 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808796 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808796"> <li> <div class="comment"> <table class="comment-table" commentId="808896" commentParentId="808796"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808896" href="?#comment-808896" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808796" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808896" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808896"> <div class="moveup"> <div class="ttypography"><p>But that's exactly what I did, and the final answer is the sum of the array — sum of all subarrays. <a href="https://codeforces.com/contest/1541/submission/120611950">120611950</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808896 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808896 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808896"> <li> <div class="comment"> <table class="comment-table" commentId="808941" commentParentId="808896"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808941" href="?#comment-808941" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808896" style="font-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="808941" 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="808941" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808941"> <div class="moveup"> <div class="ttypography"><p>No, that's not what you did. To compute the answer via the method described above, you would have to compute how many elements are lesser than the current element at any given iteration and add them and also keep and their count using a Fenwick tree/ BIT. That's the incorrect approach though because sorting would be more optimal.</p></div> </div> </div> <div class="reply info"> <a class="comment-808941 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808941 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808941"> <li> <div class="comment"> <table class="comment-table" commentId="808952" commentParentId="808941"> <tr> <td class="left"> <div style="position: absolute; left: 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/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808952" href="?#comment-808952" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808941" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808952" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808952"> <div class="moveup"> <div class="ttypography"><p>Sorry if I misunderstood things. mangat_angad only mentioned adding negative weighed edges to the 1-&gt;2-&gt;3-&gt;...N graph, which is what I thought to arrive at my solution. The array I mentioned is indeed sorted and formed by distance differences which are the weights in the 1-&gt;2-&gt;3-&gt;...N graph. Unfortunately I'm still too noob to understand the tree structures you mentioned.</p></div> </div> </div> <div class="reply info"> <a class="comment-808952 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808952 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808952"> <li> <div class="comment"> <table class="comment-table" commentId="808955" commentParentId="808952"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808955" href="?#comment-808955" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808952" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808955" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808955"> <div class="moveup"> <div class="ttypography"><p>Nothing unfortunate about it, logic trumps everything </p></div> </div> </div> <div class="reply info"> <a class="comment-808955 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808955 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808955"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808797" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808797" href="?#comment-808797" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808797" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808797"> <div class="moveup"> <div class="ttypography"><p>Just want to apologize to authors for the stupidest question, I misread the task..</p></div> </div> </div> <div class="reply info"> <a class="comment-808797 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808797 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808797"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808813" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808813" href="?#comment-808813" style="font-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="808813" 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="808813" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808813"> <div class="moveup"> <div class="ttypography"><p>Can someone tell me the meaning of this line in problem Div2D/Div1B<br /></p> <blockquote><p>Note that, until reaching, l every possible process still has the same probability of reaching b before a. Therefore, we can assume that the process has reached l and calculate the probability from there.</p> </blockquote><p>What same probability are they talking about?</p></div> </div> </div> <div class="reply info"> <a class="comment-808813 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808813 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808813"> <li> <div class="comment"> <table class="comment-table" commentId="808831" commentParentId="808813"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808831" href="?#comment-808831" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808813" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808831" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808831"> <div class="moveup"> <div class="ttypography"><p>Here's what it's trying to say:</p><p>Suppose we start by marking the root. To mark a or b, we must first mark the lca, so we may assume that the lca has just been marked.</p></div> </div> </div> <div class="reply info"> <a class="comment-808831 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808831 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808831"> <li> <div class="comment"> <table class="comment-table" commentId="808840" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808840" href="?#comment-808840" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808840" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808840"> <div class="moveup"> <div class="ttypography"><p>And what does this line mean? <em>&quot;The problem can be rephrased as having two stacks of size dist(l,a) and dist(l,b) with an arbitrary p to remove a node from one of the two stack (and 1−2p to nothing) and finding the probability that dist(l,b) reaches zero before dist(l,a).&quot;</em></p></div> </div> </div> <div class="reply info"> <a class="comment-808840 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808840 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808840"> <li> <div class="comment"> <table class="comment-table" commentId="808857" commentParentId="808840"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808857" href="?#comment-808857" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808840" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808857" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808857"> <div class="moveup"> <div class="ttypography"><p>Once you've reached the lca $$$l$$$, in a single step you either step closer to $$$a$$$, step closer to $$$b$$$, or step closer to neither.</p></div> </div> </div> <div class="reply info"> <a class="comment-808857 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808857 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808857"> <li> <div class="comment"> <table class="comment-table" commentId="808862" commentParentId="808857"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808862" href="?#comment-808862" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808857" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808862" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808862"> <div class="moveup"> <div class="ttypography"><p>Can you add implementation for this problem please?</p></div> </div> </div> <div class="reply info"> <a class="comment-808862 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808862 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808862"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808849" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808849" href="?#comment-808849" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808849" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808849"> <div class="moveup"> <div class="ttypography"><p>So, we mark lca first (of course). But why wouldn't it affect the final probability of reaching b before a? I mean, why is it sufficient to calculate the probability after marking lca?</p></div> </div> </div> <div class="reply info"> <a class="comment-808849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808849"> <li> <div class="comment"> <table class="comment-table" commentId="808873" commentParentId="808849"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808873" href="?#comment-808873" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808849" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808873" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808873"> <div class="moveup"> <div class="ttypography"><p>Before marking the lca, there is no way to make more progress towards $$$b$$$ than $$$a$$$ or vice versa. The subset of marked vertices also does not change the probability of moving towards $$$a$$$ or $$$b$$$ after reaching the lca because we're choosing uniformly at random and exactly two vertices are of interest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808873 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808873 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808873"> <li> <div class="comment"> <table class="comment-table" commentId="808883" commentParentId="808873"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808883" href="?#comment-808883" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808873" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808883" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808883"> <div class="moveup"> <div class="ttypography"><p>Now I get it. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808883 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808883 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808883"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808814" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808814" href="?#comment-808814" style="font-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="808814" 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="808814" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808814"> <div class="moveup"> <div class="ttypography"><p>So, my Solution for <strong>Div1 Problem B</strong> / <strong>Div2 Problem D</strong> / <strong>1540B — Tree Array</strong>:</p><p>Chose two Nodes $$$A$$$ and $$$B$$$ with $$$A&gt;B$$$. </p><p><strong>First DFS:</strong> Find the path from $$$A$$$ to $$$B$$$. I call it $$$path_p$$$. On $$$path_p$$$ mark the distance to $$$B$$$ for each node. </p><p><strong>Second DFS:</strong> For each remaining node $$$N$$$ find the shortest path to $$$path_p$$$. It will hit it at some node of the $$$path_p$$$ which has some distance $$$D$$$ marked on it. We mark $$$N$$$ with $$$D$$$. (See comment below for image.)</p><p><strong>Calculation:</strong> For each node $$$N$$$ we can calculate $$$P_i$$$. $$$P_i$$$ is the probability to reach Node $$$B$$$ before we reach Node $$$A$$$. We sum $$$P_i$$$ for each node. $$$P_i$$$ is also the probability, that the pair of Nodes $$$A$$$ and $$$B$$$ with starting node $$$N$$$ will contribute to the inversion sum. </p><p><strong>Iteration:</strong> We need to repeat this for each pair $$$A$$$ and $$$B$$$. In the end we divide the answer by $$$n$$$, the amount of nodes (the probability to start with Node $$$N$$$). </p><p>This algorithm is $$$O(N^3)$$$. See my Solution <a href="/contest/1540/submission/120603369" title="Посылка 120603369 от OleschY">120603369</a></p> <div class="spoiler"><b class="spoiler-title">How to calculate P_i</b><div class="spoiler-content" style="display: none;"><p>I wrote myself a small helper DP-program to find the regularities. Let $$$D$$$ be the Distance between $$$A$$$ and $$$B$$$ and $$$d$$$ be the distance from the node $$$N$$$ to $$$B$$$. My educated guess was: $$$P_i=\frac{\sum_{i=0}^{d-1}\binom{D-1}{i} }{2^{D-1}}$$$</p> <div class="spoiler"><b class="spoiler-title">Helper Program</b><div class="spoiler-content" style="display: none;"><p>It checks for a path of some length for each Intervall $$$[A,B]$$$ which is already visited, what the probability to reach one node before the other is. </p> <pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; int solve(int n) { vector&lt;vector&lt;double&gt;&gt; dp(n, vector&lt;double&gt;(n, 0)); for(int i = 0; i &lt; n; ++i) { dp[0][i] = 1; dp[i][n - 1] = 0; } dp[0][n - 1] = -1; for(int w = n; w &gt;= 0; w--) { for(int i = 1; i + w &lt; n - 1; i++) { int l = i; int r = w + i; dp[l][r] = 0.5 * (dp[l - 1][r] + dp[l][r + 1]); } } cout &lt;&lt; n &lt;&lt; &quot;\n\n&quot;; for(int i = 0; i &lt; n; i++) { cout &lt;&lt; dp[i][i]*(1&lt;&lt;(n-2)) &lt;&lt; &quot;\n&quot;; } cout &lt;&lt; &quot;\n\n\n\n&quot;; return 0; } //====================== // Technical stuff //====================== int main() { int ntest = 12; for(int test = 2; test &lt; ntest; ++test) { solve(test); } return 0; } </code></pre></div></div></div></div></div> </div> </div> <div class="reply info"> <a class="comment-808814 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808814 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808814"> <li> <div class="comment"> <table class="comment-table" commentId="808843" commentParentId="808814"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808843" href="?#comment-808843" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808814" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808843" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808843"> <div class="moveup"> <div class="ttypography"><p>Can you explain your solution in a little bit more detail? :')</p></div> </div> </div> <div class="reply info"> <a class="comment-808843 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808843 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808843"> <li> <div class="comment"> <table class="comment-table" commentId="808869" commentParentId="808843"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808869" href="?#comment-808869" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808843" style="font-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="808869" 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="808869" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808869"> <div class="moveup"> <div class="ttypography"><p>Oof, I can give you an image, that shows how the distances from the two DFS are distributed on an example. You can see Nodes $$$A$$$ and $$$B$$$ and the numbers are the distances we write into the nodes. </p><p><img alt=" " src="/predownloaded/d8/2f/d82f98ecd2c1b4bd15b3c40e62476f6ae2741a64.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>If you have specific questions about some steps go ahead and ask. </p></div> </div> </div> <div class="reply info"> <a class="comment-808869 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808869 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808869"> <li> <div class="comment"> <table class="comment-table" commentId="810069" commentParentId="808869"> <tr> <td class="left"> <div style="position: absolute; left: 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/Mrajaryan" style="position: relative;"> <img src='https://userpic.codeforces.org/1377953/avatar/e904b3a3a2eac1ad.jpg'/> </a> <div><a href="/profile/Mrajaryan" title="Newbie Mrajaryan" class="rated-user user-gray">Mrajaryan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 15:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810069" href="?#comment-810069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808869" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810069" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1377953" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810069"> <div class="moveup"> <div class="ttypography"><p>what does the dp states mean in your helper program? I am unable to understand. Can you please explain?</p></div> </div> </div> <div class="reply info"> <a class="comment-810069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810069"> <li> <div class="comment"> <table class="comment-table" commentId="810097" commentParentId="810069"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 18:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810097" href="?#comment-810097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-810069" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810097"> <div class="moveup"> <div class="ttypography"><p>You have Nodes $$$1$$$ through $$$N$$$, neighbouring IDs are connected. The state $$$dp[l][r]$$$ is the probability, that node $$$N$$$ will be reached before node $$$1$$$ with all the nodes $$$l$$$ through $$$r$$$ marked already. Obviously $$$dp[1][x]=0$$$ and $$$dp[x][N]=1$$$ ($$$dp[1][N]$$$ can't happen). The recurrence is $$$dp[l][r]=(dp[l-1][r]+dp[l][r+1])/2$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-810097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808818" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808818" href="?#comment-808818" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808818" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808818"> <div class="moveup"> <div class="ttypography"><p>I can't grasp the editorial of Div 2 D/ Div 1 B. Can somebody provide a more intuitive explanation?</p></div> </div> </div> <div class="reply info"> <a class="comment-808818 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808818 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808818"> <li> <div class="comment"> <table class="comment-table" commentId="808821" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:45">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808821" href="?#comment-808821" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808821" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808821"> <div class="moveup"> <div class="ttypography"><p>same :(</p></div> </div> </div> <div class="reply info"> <a class="comment-808821 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808821 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808821"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808861" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808861" href="?#comment-808861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808861" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808861"> <div class="moveup"> <div class="ttypography"><p>Step 1. use linearity of expectation. The answer is</p> <center>$$$\sum_{a&lt;b} P(b\text{ appears before }a). $$$</center><p>Step 2: Observe that if we start by marking a vertex $$$c$$$ on the path between $$$a$$$ and $$$b$$$, and suppose the next marked vertex on the path is $$$d$$$. Then, the probability that $$$d$$$ is between $$$c$$$ and $$$a$$$ and the probability that $$$d$$$ is between $$$c$$$ and $$$b$$$ are both $$$1/2$$$. This is because there are only two choices for $$$d$$$ and we're choosing uniformly at random. This means that the answer only depends on $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p><p>Step 3: run a dp to calculate the probability that we mark $$$b$$$ before $$$a$$$ given $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808861"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808833" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808833" href="?#comment-808833" style="font-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="808833" 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="808833" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-72" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-72</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808833"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin &gt;&gt; t; while(t--){ int n; cin &gt;&gt; n; long long arr[n]; for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0; for(int i = 0; i &lt; n — 1; i++){ for(int j = arr[i] — 2 — i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } } } cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;; } return 0; }</p><p>/* Accepted code A different approach using arrays (as I don't know what vectors are, haven't read that) I hope this is a optimal approach. Any suggestions related to this are whole-heartedly welcomed. Also, please guide me how could I have optimized the code to a much extent. Thanks in advance! Keep programming! */</p></div> </div> </div> <div class="reply info"> <a class="comment-808833 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808833 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808833"> <li> <div class="comment"> <table class="comment-table" commentId="808844" commentParentId="808833"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808844" href="?#comment-808844" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808833" style="font-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="808844" 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="808844" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-35" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808844"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-808844 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808844 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808844"> <li> <div class="comment"> <table class="comment-table" commentId="808863" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808863" href="?#comment-808863" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808863" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808863"> <div class="moveup"> <div class="ttypography"><p>Not studied yet, I'm still a beginner, but planning to start soon. Thanks for the guidance.</p></div> </div> </div> <div class="reply info"> <a class="comment-808863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808863"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808879" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808879" href="?#comment-808879" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808879" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808879"> <div class="moveup"> <div class="ttypography"><p>once upon a time, I also did problems while not know what vectors are. sad times :'(</p></div> </div> </div> <div class="reply info"> <a class="comment-808879 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808879 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808879"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808926" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808926" href="?#comment-808926" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808926" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808926"> <div class="moveup"> <div class="ttypography"><p>There's no issue in not knowing vectors. Yes they are important I agree but not knowing vectors should not be discouraged. I became expert here without knowing anything about vectors plus he is a beginner so he shouldn't be discouraged like this.</p></div> </div> </div> <div class="reply info"> <a class="comment-808926 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808926 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808926"> <li> <div class="comment"> <table class="comment-table" commentId="808927" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Tech.Maniac" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Tech.Maniac" title="Expert Tech.Maniac" class="rated-user user-blue">Tech.Maniac</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808927" href="?#comment-808927" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808927" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1242860" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808927"> <div class="moveup"> <div class="ttypography"><p>+1, I agree with you. Same I was expert last year solely using arrays</p></div> </div> </div> <div class="reply info"> <a class="comment-808927 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808927 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808927"> <li> <div class="comment"> <table class="comment-table" commentId="809201" commentParentId="808927"> <tr> <td class="left"> <div style="position: absolute; left: 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/Yash.Amin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Yash.Amin" title="Specialist Yash.Amin" class="rated-user user-cyan">Yash.Amin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809201" href="?#comment-809201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808927" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809201" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-28" data-commentUserId="1226462" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-28</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809201"> <div class="moveup"> <div class="ttypography"><p>Bas kar bsdk kitna jhooth bolega</p></div> </div> </div> <div class="reply info"> <a class="comment-809201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809201"> <li> <div class="comment"> <table class="comment-table" commentId="809215" commentParentId="809201"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809215" href="?#comment-809215" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809215" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809215"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-blue" href="/profile/Yash.Amin" title="Эксперт Yash.Amin">Yash.Amin</a> Could you please refrain from using foul language on educational discussions. Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-809215 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809215 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809215"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808928" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808928" href="?#comment-808928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808928" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808928"> <div class="moveup"> <div class="ttypography"><p>Ah my bad, I did not want to come across as being arrogant, but I was genuinely confused that some people did not know vectors although they are using C++.</p></div> </div> </div> <div class="reply info"> <a class="comment-808928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808928"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808839" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamkiller04" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dreamkiller04" title="Newbie dreamkiller04" class="rated-user user-gray">dreamkiller04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808839" href="?#comment-808839" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2089608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808839"> <div class="moveup"> <div class="ttypography"><p>Please add implementations too.</p></div> </div> </div> <div class="reply info"> <a class="comment-808839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808839"> <li> <div class="comment"> <table class="comment-table" commentId="809106" commentParentId="808839"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809106" href="?#comment-809106" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808839" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809106" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809106"> <div class="moveup"> <div class="ttypography"><p>Simply running two loops and checking every case would give a TLE. So, we might want to minimize the number of operations. For this, we would only consider the cases where the sum of indices is a multiple of an element.</p><p>For this, we would first create two loops, one within the other, first loop iterating i from 0 to (n — 1) with an incrementation of 1. By observation, we can see that the first index for which the sum of indices will be a multiple of arr[i] is (arr[i] — 2 — i).</p><p>So, in the nested loop we will run j = (arr[i] — 2 — i) till (n — 1) with an incrementation of arr[i]. We would ignore the cases where j &lt; 0 or j &gt;= n.</p><p>Finally, we need to check for how many cases this holds (arr[i] * arr[j] = i + j + 2 and j &gt; i).</p><p>Suggestions are welcomed!</p></div> </div> </div> <div class="reply info"> <a class="comment-809106 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809106 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809106"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808842" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808842" href="?#comment-808842" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808842" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-64" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-64</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808842"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){</p><p>ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);</p><p>int t;</p><p>cin &gt;&gt; t;</p><p>while(t--){</p><p>int n;</p> <pre>cin &gt;&gt; n;</pre><p>long long arr[n];</p> <pre>for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0;</pre><p>for(int i = 0; i &lt; n — 1; i++){</p> <pre>for(int j = arr[i] &amp;mdash; 2 &amp;mdash; i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } }</pre><p>}</p><p>cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;;</p><p>}</p> <pre>return 0;</pre><p>}</p><p>/* Accepted code</p><p>A different approach using arrays (as I don't know what vectors are, haven't read that)</p><p>I hope this is a optimal approach.</p><p>Any suggestions related to this are whole-heartedly welcomed.</p><p>Also, please guide me how could I have optimized the code to a much extent.</p><p>Thanks in advance!</p><p>Keep programming! </p><p>*/</p></div> </div> </div> <div class="reply info"> <a class="comment-808842 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808842 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808842"> <li> <div class="comment"> <table class="comment-table" commentId="808851" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808851" href="?#comment-808851" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808851" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808851"> <div class="moveup"> <div class="ttypography"><p>Use spoilers for writing codes, please!</p></div> </div> </div> <div class="reply info"> <a class="comment-808851 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808851 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808851"> <li> <div class="comment"> <table class="comment-table" commentId="808870" commentParentId="808851"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808870" href="?#comment-808870" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808851" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808870" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808870"> <div class="moveup"> <div class="ttypography"><p>Actually, this is my first comment. Don't know much of this stuff as of now, but I'll surely take care of it the very next time.</p></div> </div> </div> <div class="reply info"> <a class="comment-808870 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808870 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808870"> <li> <div class="comment"> <table class="comment-table" commentId="809760" commentParentId="808870"> <tr> <td class="left"> <div style="position: absolute; left: 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/sus" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sus" title="Pupil sus" class="rated-user user-green">sus</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 05:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809760" href="?#comment-809760" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808870" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809760" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1749651" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809760"> <div class="moveup"> <div class="ttypography"><p>what problem is your code for</p></div> </div> </div> <div class="reply info"> <a class="comment-809760 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809760 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809760"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808884" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sevlll777" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sevlll777" title="Grandmaster sevlll777" class="rated-user user-red">sevlll777</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808884" href="?#comment-808884" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808884" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="839333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808884"> <div class="moveup"> <div class="ttypography"><p>NICE CODESTYLE!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-808884 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808884 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808884"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809084" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cj2021" style="position: relative;"> <img src='https://userpic.codeforces.org/1927237/avatar/b64ff59bd9dcf385.jpg'/> </a> <div><a href="/profile/cj2021" title="Newbie cj2021" class="rated-user user-gray">cj2021</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809084" href="?#comment-809084" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809084" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1927237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809084"> <div class="moveup"> <div class="ttypography"><p>What is &amp;mdash?</p><p>Just curious to know as haven't seen it before.</p></div> </div> </div> <div class="reply info"> <a class="comment-809084 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809084 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809084"> <li> <div class="comment"> <table class="comment-table" commentId="809097" commentParentId="809084"> <tr> <td class="left"> <div style="position: absolute; left: 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/klahsiv" style="position: relative;"> <img src='https://userpic.codeforces.org/1590145/avatar/1bf86ae3d48e55b.jpg'/> </a> <div><a href="/profile/klahsiv" title="Expert klahsiv" class="rated-user user-blue">klahsiv</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809097" href="?#comment-809097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809084" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590145" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809097"> <div class="moveup"> <div class="ttypography"><p>it is minus (-).</p></div> </div> </div> <div class="reply info"> <a class="comment-809097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808848" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/willy108" style="position: relative;"> <img src='https://userpic.codeforces.org/1439320/avatar/d7f79ed4e8b32e9a.jpg'/> </a> <div><a href="/profile/willy108" title="Master willy108" class="rated-user user-orange">willy108</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808848" href="?#comment-808848" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808848" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="1439320" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808848"> <div class="moveup"> <div class="ttypography"><p>Div2 B can also be done in O(NsqrtN). We know that for a given pair of indeces i+j &lt; 2n, so any pair that a[i] * a[j] &lt; 2n will have to have one of the two terms be &lt;= sqrt(n) (with some off by one errors of course). So the algorithm is to store an array of pairs [array value, index] and sort that array by the value. If the array value is &lt;= sqrt(2n) we can naively loop over the rest of the array in O(n) time and check (be careful about overcount), and if the value is &gt; sqrt(n), we can ignore it. This works since when a[i] * a[j] &lt; 2n one of a[i] or a[j] has to be &lt;= sqrt(2n) and as a result, every pair will be counted.</p></div> </div> </div> <div class="reply info"> <a class="comment-808848 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808848 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808848"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808860" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bcollet" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bcollet" title="Master bcollet" class="rated-user user-orange">bcollet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808860" href="?#comment-808860" style="font-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="808860" 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="808860" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="858059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808860"> <div class="moveup"> <div class="ttypography"><p>I don't understand in div1 C why it's prefix of b, in the case i=3 we have $$$a_1+a_2+a_3=f_1+f_1+b_1+f_1+b_1+b_2$$$ so $$$f_1=(ap_i-2b_1-b_2)$$$ I believe the general formula is something in the taste of $$$f_1=(ap_i-ibp_{i-1}+bpt_{i-1})/i$$$ where bpt_i=b_1+2b_2+...+ib_i, I think I miss something<br />Edit: corrected</p></div> </div> </div> <div class="reply info"> <a class="comment-808860 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808860 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808860"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808865" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ParsaS" style="position: relative;"> <img src='https://userpic.codeforces.org/1590150/avatar/dc2d8c002d2c5e1e.jpg'/> </a> <div><a href="/profile/ParsaS" title="Candidate Master ParsaS" class="rated-user user-violet">ParsaS</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808865" href="?#comment-808865" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808865" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590150" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808865"> <div class="moveup"> <div class="ttypography"><p>Nice problems. thanks for almost fast editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-808865 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808865 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808865"> <li> <div class="comment"> <table class="comment-table" commentId="808871" commentParentId="808865"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/E404_Not_Found" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/E404_Not_Found" title="Expert E404_Not_Found" class="rated-user user-blue">E404_Not_Found</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808871" href="?#comment-808871" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808865" style="font-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="808871" 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="808871" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1662858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808871"> <div class="moveup"> <div class="ttypography"><p>Yes thanks for fast editorial :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808871 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808871 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808871"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808890" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vikash_8090_b" style="position: relative;"> <img src='https://userpic.codeforces.org/1969032/avatar/a0f23c893ae54e74.jpg'/> </a> <div><a href="/profile/vikash_8090_b" title="Newbie vikash_8090_b" class="rated-user user-gray">vikash_8090_b</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808890" href="?#comment-808890" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808890" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="1969032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808890"> <div class="moveup"> <div class="ttypography"><p>is there anyone who can't even solve one question of today's contest ..</p></div> </div> </div> <div class="reply info"> <a class="comment-808890 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808890 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808890"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808892" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808892" href="?#comment-808892" style="font-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="808892" 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="808892" class="CommentVoteFrame" data-commentRating="-6" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808892"> <div class="moveup"> <div class="ttypography"><p>Deleted :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808892 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808892 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808892"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808918" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prituladima" style="position: relative;"> <img src='https://userpic.codeforces.org/116750/avatar/ca46d0256a294b26.jpg'/> </a> <div><a href="/profile/prituladima" title="Pupil prituladima" class="rated-user user-green">prituladima</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808918" href="?#comment-808918" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808918" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="116750" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808918"> <div class="moveup"> <div class="ttypography"><p>Please explain div2c/div1a problem a little bit more. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808918 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808918 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808918"> <li> <div class="comment"> <table class="comment-table" commentId="808921" commentParentId="808918"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808921" href="?#comment-808921" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808918" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808921" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808921"> <div class="moveup"> <div class="ttypography"><p>Try out this <a href="https://youtube.com/c/MagentaCobra">channel</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808921 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808921 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808921"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808950" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jakab922" style="position: relative;"> <img src='https://userpic.codeforces.org/53532/avatar/f9515e974f3ebcb1.jpg'/> </a> <div><a href="/profile/jakab922" title="Specialist jakab922" class="rated-user user-cyan">jakab922</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808950" href="?#comment-808950" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808950" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="53532" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808950"> <div class="moveup"> <div class="ttypography"><p>I don't really understand the need for a recursive function for the stack emptying probabilities in <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a>. I mean given that you have a stack of size <code>n</code> and and <code>m</code> you can basically have an array of size <code>n + m</code> filled with <code>0</code>s and <code>1</code>s where <code>0</code> at the <code>i</code>th place means that the <code>i</code>th element was taken from the first stack. Any such array which has <code>n</code> <code>0</code>s and <code>m</code> <code>1</code>s correspond to one process and it's easy to see that whoever takes the last spot in the array gets emptied later which gives an easy way to calculate the probabilities. Namely $$$\binom{n + m - 1}{n - 1} / \binom{n + m}{n}$$$ for the first and similar to the other. </p></div> </div> </div> <div class="reply info"> <a class="comment-808950 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808950 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808950"> <li> <div class="comment"> <table class="comment-table" commentId="808959" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cuom1999" style="position: relative;"> <img src='https://userpic.codeforces.org/253776/avatar/934152bc42a0b10c.jpg'/> </a> <div><a href="/profile/cuom1999" title="Grandmaster cuom1999" class="rated-user user-red">cuom1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808959" href="?#comment-808959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="253776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808959"> <div class="moveup"> <div class="ttypography"><p>If $$$m=2$$$ and $$$n=1$$$, your approach gives $$$\frac{1}{3}$$$. The correct answer should be $$$\frac{1}{4}$$$. </p><p>P/S: I'm also curious if there is any combinatoric approach for this,<a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808959"> <li> <div class="comment"> <table class="comment-table" commentId="809004" commentParentId="808959"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809004" href="?#comment-809004" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809004" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809004"> <div class="moveup"> <div class="ttypography"><p>I would guess that there’s no easy closed form. You can evaluate in $$$O(n)$$$ however by counting right up paths from $$$(a,0)$$$ to $$$(x,y)$$$ for all $$$a$$$ and multiplying by $$$2^{-steps}$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-809004 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809004 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809004"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809366" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/geekpradd" style="position: relative;"> <img src='https://userpic.codeforces.org/367430/avatar/427394aa7f5a63a0.jpg'/> </a> <div><a href="/profile/geekpradd" title="Candidate Master geekpradd" class="rated-user user-violet">geekpradd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809366" href="?#comment-809366" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809366" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="367430" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809366"> <div class="moveup"> <div class="ttypography"><p>The problem with this is that all the possibilities are not equilikely, consider $$$m=2, n=1$$$ and let $$$1$$$ denote entries from the stack of size $$$n$$$. Then the probability of obtaining $$$100$$$ is $$$1/2$$$, while obtaining $$$010$$$ and $$$001$$$ has a probability of $$$1/4$$$. Your approach assumes a uniform prior probability (in which case the answer is indeed $$$1/3$$$ whereas here it is $$$1/4$$$ which is the probability of getting $$$001$$$)</p></div> </div> </div> <div class="reply info"> <a class="comment-809366 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809366 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809366"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thunderboltz" style="position: relative;"> <img src='https://userpic.codeforces.org/1170396/avatar/4f017b259605bc5c.jpg'/> </a> <div><a href="/profile/thunderboltz" title="Newbie thunderboltz" class="rated-user user-gray">thunderboltz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808951" href="?#comment-808951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170396" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808951"> <div class="moveup"> <div class="ttypography"><p>Problem Div2C/Div1A, Plz somebody explain 3rd hint. I didn't get why this condition must be true </p><p><code>The sum of the values of edges with positive weight must be ≥ the maximum value in the array.</code></p></div> </div> </div> <div class="reply info"> <a class="comment-808951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808951"> <li> <div class="comment"> <table class="comment-table" commentId="808995" commentParentId="808951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808995" href="?#comment-808995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808995" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808995"> <div class="moveup"> <div class="ttypography"><p>I like to think about C this way: The cheapest node is the root, and the most expensive node, X, is the one with the highest value, D. Therefore no matter how we make our edges, we need at least 1 path from node to X with distance D. So let's build 1 single edge of positive weight from 1 to X with weight D.</p><p>Now from node X, all other nodes are &lt;= D. We can use negative edges to go there. Now the problem just becomes &quot;assign as many negative edges as possible&quot; to the rest of the nodes. </p></div> </div> </div> <div class="reply info"> <a class="comment-808995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808995"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808971" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808971" href="?#comment-808971" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808971" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808971"> <div class="moveup"> <div class="ttypography"><p>In problem <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a> I agree with everything up to:</p> <blockquote><p>Once l is reached, we now note that the probability that the process &quot;gets closer&quot; to b is always equal to the probability of getting closer to a.</p> </blockquote><p>I agree with this quote if it was about each individual set of marked nodes and single step for them. Because for any individual set of marked nodes, those probabilities is just one over the number of options at the moment. But I don't understand why I should forget about everything else what happens with other parts of tree, because after single step which is neither towards <strong>a</strong> neither towards <strong>b</strong>, the number of options (nodes we can mark on next step) may change.</p></div> </div> </div> <div class="reply info"> <a class="comment-808971 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808971 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808971"> <li> <div class="comment"> <table class="comment-table" commentId="809006" commentParentId="808971"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809006" href="?#comment-809006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808971" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809006" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809006"> <div class="moveup"> <div class="ttypography"><p>That is correct, but to see how it stays the same you can think of it inductively. Use strong induction and assume probability is the same no matter what the state of the tree is. Then from $$$(x,y)$$$ you always have an equal probability of ending up in one of the two states you can transition to because $$$p$$$ is always the same. Every scenario you enter one state, there’s another scenario with the same probability that enters the other state. So, the probability of entering one of the two states is the same as the other, thus $$$0.5$$$. Hopefully that makes things more clear.</p></div> </div> </div> <div class="reply info"> <a class="comment-809006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809006"> <li> <div class="comment"> <table class="comment-table" commentId="809113" commentParentId="809006"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809113" href="?#comment-809113" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809006" style="font-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="809113" 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="809113" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809113"> <div class="moveup"> <div class="ttypography"><p>Oh thanks, it's clear now. So, base of induction is when only <strong>l</strong> reached, and we can show that probability to make step towards <strong>a</strong> and <strong>b</strong> is same because for each individual set you can go from <strong>l</strong> to <strong>b</strong> instead of going from <strong>l</strong> into <strong>a</strong>, using exactly same steps in between (those steps which doesn't change distances to <strong>a</strong> and <strong>b</strong>). And similar holds for next steps.</p></div> </div> </div> <div class="reply info"> <a class="comment-809113 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809113 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809113"> <li> <div class="comment"> <table class="comment-table" commentId="821713" commentParentId="809113"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 08:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821713" href="?#comment-821713" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809113" style="font-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="821713" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="821713" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-821713"> <div class="moveup"> <div class="ttypography"><p>Can you explain this?</p><p>Assume $$$X$$$ is initially node we chose. Then define a function $$$g$$$ :</p><p>$$$g[a][b][STATE]$$$ = probability to reach a before b while state of the tree we reach is $$$STATE$$$, and $$$a$$$, $$$b$$$ is length of path.</p><p><img alt=" " src="/predownloaded/c2/32/c232d053fe3fbd1dedc06e56db58a7c139157987.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>follow the image, I can see : $$$g[a][b][STATE_x] = \frac{1}{4} (g[a][b][STATE_d] + g[a][b][STATE_e] + g[a — 1][b][closer_a] + g[a][b — 1][closer_b])$$$</p><p>It can easy see that the probability can change. Or I wrong in some where?</p></div> </div> </div> <div class="reply info"> <a class="comment-821713 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821713 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821713"> <li> <div class="comment"> <table class="comment-table" commentId="821861" commentParentId="821713"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 18:25">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821861" href="?#comment-821861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821713" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="821861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-821861"> <div class="moveup"> <div class="ttypography"><p>I'll hide my long explanation under spoiler</p> <div class="spoiler"><b class="spoiler-title">horrible wall of text</b><div class="spoiler-content" style="display: none;"><p>To put things into words, I want to define some things. First, suppose we marked some $$$s_1, s_2, s_3 ... s_k$$$ vertices in exact this order. Then, let $$$P(s)$$$ to be probability to mark them in this sequence. It can be decomposed into $$$P(s) = p_1 \cdot p_2 \cdot p_3 \cdot ... \cdot p_k$$$ where $$$p_i = 1/o_{i-1}$$$ where $$$o_i$$$ is number of options at step $$$i$$$ — number of opened vertices, except $$$p_0 = 1/n$$$, or $$$o_0 = n$$$.</p><p>Then, let $$$l = LCA(a, b)$$$ where $$$LCA$$$ is lowest common ancestor. Then, let $$$x_v$$$ to be some sort of 'cost'. For each $$$v$$$ on path between $$$a$$$ and $$$l$$$ it will be distance to $$$l$$$, and $$$-1$$$ everywhere else. Similarly, for each $$$v$$$ on path between $$$b$$$ and $$$l$$$ let $$$y_v$$$ to be distance to $$$l$$$ and $$$-1$$$ everywhere else. Let</p> <center>$$$ A(s) = \max\limits_{v\in s}x_v \\ B(s) = \max\limits_{v\in s}y_v $$$</center><p>Then $$$A(s)$$$ is equal to how far we reach $$$a$$$, and $$$B(s)$$$ is equal to how far we reach $$$b$$$. Let say we are in situation $$$(A(s), B(s))$$$ after marking $$$s$$$, and therefore situation is pair of numbers. Situation $$$(-1,-1)$$$ corresponds that no vertex is marked on path from $$$a$$$ to $$$b$$$. Situation $$$(0,0)$$$ corresponds to only $$$l$$$ marked on path from $$$a$$$ to $$$b$$$. And situation $$$(1,0)$$$ corresponds to $$$l$$$ and single vertex towards $$$a$$$ is marked.</p><p>Finally, let say sequence of marks $$$s$$$ reached state $$$(A(s), B(s))$$$ if either $$$A(s) = x_{s_k}$$$ or $$$B(s) = y_{s_k}$$$, in other words, last vertex is on path from $$$a$$$ to $$$b$$$ and it did change situation.</p><p>Now, what we want to prove is following:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha+1,\beta)} P(s) = \sum\limits_{s\;reached\;(\alpha,\beta+1)} P(s)$$$</center><p><strong>For some fixed</strong> $$$s_1$$$, which is root we chosen. And the way we prove it is that $$$s$$$ that is reached $$$(\alpha+1,\beta)$$$ consists of $$$u$$$ that reached $$$(\alpha,\beta)$$$ plus additional steps: $$$w$$$ plus $$$s_k$$$. So $$$s = u..w..s_k$$$ where $$$..$$$ is concatenation. It's easy to see what none of vertices from $$$w$$$ is on path from $$$a$$$ to $$$b$$$. Also, it's easy to see that we could instead of choosing $$$s_k$$$ could choose vertex $$$z$$$ towards $$$b$$$, and it would have same probability. In other words $$$P(s) = P(u..w..z)$$$. And this $$$u..w..z$$$ should reach state $$$(\alpha, \beta+1)$$$. So it should be in right side sum of our equation we want to prove.</p><p>So, for any $$$s$$$ from left sum, we can make $$$s'$$$ from right sum in unique way, and it will have same $$$P(s) = P(s')$$$. Similarly, for any $$$s$$$ from right sum, we can make $$$s'$$$ from left sum in unique way, and it will have same $$$P(s) = P(s')$$$. So this is bijection, and each element from left sum corresponds to element from right sum with same value, so those sums should have same value. Therefore it's equality.</p><p>Initially I wanted to trim $$$s$$$ from $$$(\alpha+1,\beta)$$$ to $$$(\alpha,\beta)$$$ and show similar thing based on following sum:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha,\beta)} P(s)$$$</center><p>Which is probability to reach state $$$(\alpha, \beta)$$$, but luckily it didn't required. I'll use notation $$$P(reach(\alpha, \beta))$$$ for this probability.</p><p>Thing that is not covered though: why this equality can be translated into probability $$$= 1/2$$$? Well, from $$$(\alpha, \beta)$$$ you eventually will reach either $$$(\alpha+1,\beta)$$$ or $$$(\alpha,\beta+1)$$$, so you can see this as example of Law of total probability. $$$P(reach(\alpha, \beta)) = P(reach (\alpha+1, \beta)) + P(reach (\alpha, \beta+1))$$$, because events $$$(\alpha+1,\beta)$$$ and $$$(\alpha,\beta+1)$$$ are disjoint events given $$$(\alpha, \beta)$$$ is reached. And we proved they have equal probability so $$$P(reach(\alpha, \beta)) = 2\cdot P(reach (\alpha+1, \beta))$$$, so $$$P(reach (\alpha+1, \beta)) = 1/2\cdot P(reach(\alpha, \beta))$$$ which we actually use.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-821861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821861"> <li> <div class="comment"> <table class="comment-table" commentId="822027" commentParentId="821861"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/28/2021 13:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822027" href="?#comment-822027" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821861" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="822027" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822027"> <div class="moveup"> <div class="ttypography"><p>Oh, sorry, there is one missing part. We proved $$$P(reached(\alpha+1,\beta))=P(reached(\alpha,\beta+1))$$$ <strong>given</strong> $$$(\alpha,\beta)$$$ is reached, but this is actually what we need. This <strong>given</strong> condition is what I missed. Without <strong>given</strong> we could reach $$$(\alpha+1,\beta)$$$ from reaching $$$(\alpha+1,\beta-1)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-822027 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822027 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822027"> <li> <div class="comment"> <table class="comment-table" commentId="822370" commentParentId="822027"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 13:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822370" href="?#comment-822370" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822027" style="font-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="822370" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="822370" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822370"> <div class="moveup"> <div class="ttypography"><p>Thanks for amz explain. I realize that I had some missunderstand in the way we calc $$$P(reach\ A\ before\ B)$$$</p><p>This's exactly what in my mind one day ago: let $$$s = ...a...b...$$$ where $$$a$$$ and $$$b$$$ is node $$$a$$$ and node $$$b$$$, &quot;$$$...$$$&quot; mean some node between them which we chose them in exactly that order, or in other word, $$$s$$$ is state represent what we chose (exact in this order) I think $$$P(reach\ A\ before\ B)$$$ (or $$$P(A&lt;B)$$$) must be calculate in this way :</p><p>$$$P(A&lt;B) = \sum_{\substack{all\ s\ which\ a&lt;b}} P(s)$$$</p><p>But unfortunately, it's wrong (may be, or I still missunderstanding)</p><p>$$$P(A) = \sum_{\substack{all\ B[i]\ \subseteq\ A}} P(B[i])$$$ if and only if all $$$B[i]$$$ are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-822370 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822370 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822370"> <li> <div class="comment"> <table class="comment-table" commentId="822755" commentParentId="822370"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 22:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822755" href="?#comment-822755" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822370" style="font-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="822755" 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="822755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822755"> <div class="moveup"> <div class="ttypography"><p>$$$P(A &lt; B)$$$ in your terms is exactly what we need (if a = A and b = B).</p><p>I don't understand last formula, everything else looks fine.</p><p>And to find $$$P(A &lt; B)$$$ we use fact above and calculate all possible ways to reach $$$a$$$ earlier than $$$b$$$ we use $$$(\alpha, \beta)$$$ states using my notation: you either get $$$\alpha$$$ equal to dist to $$$a$$$ when $$$\beta$$$ = 0, or $$$\beta$$$ = 1, or 2, or 3...</p> <center>$$$ P(A &lt; B) = \\ =\sum\limits_{i=0}^{dist(b,l)}P(reach(dist(a,l),i)\;given\; reached(dist(a,l)-1,i)) \\ = \sum\limits_{i=0}^{dist(b,l)}P(reached(dist(a,l)-1,i))\cdot \frac{1}{2} $$$</center><p>Or you can rephrase task into other task with two kind of balls. What probability to remove all balls of one kind earlier than other, if you pick one or other kind of ball with probability 1/2.</p></div> </div> </div> <div class="reply info"> <a class="comment-822755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822755"> </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="808983" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/xsc" style="position: relative;"> <img src='https://userpic.codeforces.org/343/avatar/9eaf243b1eb8c3d4.jpg'/> </a> <div><a href="/profile/xsc" title="Specialist xsc" class="rated-user user-cyan">xsc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808983" href="?#comment-808983" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808983" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="343" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808983"> <div class="moveup"> <div class="ttypography"><p>Div2 D, O(N^4) solution <a href="/contest/1541/submission/120623566" title="Посылка 120623566 от xsc">120623566</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808983 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808983 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808983"> <li> <div class="comment"> <table class="comment-table" commentId="809278" commentParentId="808983"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DavidXu_JJ" style="position: relative;"> <img src='https://userpic.codeforces.org/2003708/avatar/623dc8036b4e9d72.jpg'/> </a> <div><a href="/profile/DavidXu_JJ" title="Expert DavidXu_JJ" class="rated-user user-blue">DavidXu_JJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809278" href="?#comment-809278" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808983" style="font-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="809278" 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="809278" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2003708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809278"> <div class="moveup"> <div class="ttypography"><p>Your code really helps me a lot in debugging,thanks.</p><p>By the way,it's weired that I get Wrong6 when I try to optimize to O(N^3*logN) by binary search on tree.</p><p>I have tested my function on other online judge and my function seems to be correct.</p></div> </div> </div> <div class="reply info"> <a class="comment-809278 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809278 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809278"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809018" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ducati" style="position: relative;"> <img src='https://userpic.codeforces.org/699102/avatar/eff3c352646e914e.jpg'/> </a> <div><a href="/profile/ducati" title="Grandmaster ducati" class="rated-user user-red">ducati</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 03:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809018" href="?#comment-809018" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809018" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="699102" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809018"> <div class="moveup"> <div class="ttypography"><p>Although Div.2 D is harder than ever, in my opinion, it's such a useful and excellent problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-809018 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809018 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809018"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809046" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KanishkGoel" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/KanishkGoel" title="Expert KanishkGoel" class="rated-user user-blue">KanishkGoel</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809046" href="?#comment-809046" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809046" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1917239" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809046"> <div class="moveup"> <div class="ttypography"><p>Is it usual for people to post solutions online during the contest like this channel? <a href="https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ">https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809046 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809046 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809046"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809051" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809051" href="?#comment-809051" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809051"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain why this submission <a href="/contest/1541/submission/120562335" title="Посылка 120562335 от Karnania7201">120562335</a> is failing for Div2 B? It would be a great help.</p></div> </div> </div> <div class="reply info"> <a class="comment-809051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809051"> <li> <div class="comment"> <table class="comment-table" commentId="809076" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809076" href="?#comment-809076" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809076" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809076"> <div class="moveup"> <div class="ttypography"><p>Bro you did not included the condition that i and j should be different i.e (i != j) because it is given in question that no are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-809076 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809076 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809076"> <li> <div class="comment"> <table class="comment-table" commentId="809079" commentParentId="809076"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:08">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809079" href="?#comment-809079" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809076" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809079" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809079"> <div class="moveup"> <div class="ttypography"><p>I think its covered as I started j from i+1. I tried that explicitly too but it didn't work. I wrote the same idea in a different way and it worked but this kind of implementation is not working.</p></div> </div> </div> <div class="reply info"> <a class="comment-809079 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809079 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809079"> <li> <div class="comment"> <table class="comment-table" commentId="809082" commentParentId="809079"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809082" href="?#comment-809082" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809079" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809082" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809082"> <div class="moveup"> <div class="ttypography"><p>yeah, you are right, I run your code using vector instead of creating memeset it worked fine, i guess there is some problem in that. <a href="https://codeforces.com/contest/1541/submission/120633207">120633207</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809082 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809082 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809082"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809081" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_NICkk" style="position: relative;"> <img src='https://userpic.codeforces.org/1543175/avatar/6084dd87f2c1cad9.jpg'/> </a> <div><a href="/profile/_NICkk" title="Expert _NICkk" class="rated-user user-blue">_NICkk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809081" href="?#comment-809081" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809081" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1543175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809081"> <div class="moveup"> <div class="ttypography"><p>Only fault in your code is that you didn't used memset correctly </p><p>I just changed your memset with this &quot; memset(ind, 0, sizeof(ind)) &quot; and it worked perfectly fine</p></div> </div> </div> <div class="reply info"> <a class="comment-809081 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809081 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809081"> <li> <div class="comment"> <table class="comment-table" commentId="809091" commentParentId="809081"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:37">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809091" href="?#comment-809091" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809081" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809091" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809091"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot to both of you. I shouldn't have used it without properly knowing about it. </p></div> </div> </div> <div class="reply info"> <a class="comment-809091 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809091 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809091"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809064" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vrintle" style="position: relative;"> <img src='https://userpic.codeforces.org/1991777/avatar/24d9007095afbbb6.jpg'/> </a> <div><a href="/profile/vrintle" title="Master vrintle" class="rated-user user-orange">vrintle</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809064" href="?#comment-809064" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809064" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1991777" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809064"> <div class="moveup"> <div class="ttypography"><p>Instead of $$$a_i \cdot a_j \leq 2n$$$, we could also check $$$a_i \cdot a_j \leq i+n$$$ which is a bit faster ($$$ \sim 62ms$$$).</p></div> </div> </div> <div class="reply info"> <a class="comment-809064 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809064 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809064"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809066" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809066" href="?#comment-809066" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809066" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809066"> <div class="moveup"> <div class="ttypography"><p>can anyone explain B. pleasant pairs more easy words?? </p></div> </div> </div> <div class="reply info"> <a class="comment-809066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809066"> <li> <div class="comment"> <table class="comment-table" commentId="809067" commentParentId="809066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809067" href="?#comment-809067" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809067" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809067"> <div class="moveup"> <div class="ttypography"><p>And also what is ask in 3rd question i cant understand what asked in it</p></div> </div> </div> <div class="reply info"> <a class="comment-809067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809067"> <li> <div class="comment"> <table class="comment-table" commentId="809070" commentParentId="809067"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809070" href="?#comment-809070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809067" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809070"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">https://www.youtube.com/watch?v=xCj_ZR5kENo</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809098" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809098" href="?#comment-809098" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809098" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809098"> <div class="moveup"> <div class="ttypography"><p>For those who are searching for a simple solution for great Graphs problems in O (nlogn). <a href="https://codeforces.com/contest/1541/submission/120600816">https://codeforces.com/contest/1541/submission/120600816</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809098 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809098 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809098"> <li> <div class="comment"> <table class="comment-table" commentId="809119" commentParentId="809098"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fjvzr" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/fjvzr" title="Newbie fjvzr" class="rated-user user-gray">fjvzr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809119" href="?#comment-809119" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809098" style="font-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="809119" 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="809119" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1623986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809119"> <div class="moveup"> <div class="ttypography"><p>Bro can u explain this soln????? i thought of taking all pairs that give negative edges except for the adjacent pairs.... bt getting wrong ans in 3rd 4th test case.....</p><p>while(n&gt;2) { sum-=(n-2)*(llabs(a[j]-a[i])); n--; // n = size i++; // i = 0 j--; // j = n-1 } cout&lt;&lt;sum&lt;&lt;endl;</p><p><a href="https://codeforces.com/contest/1541/submission/120636509">mysoln</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809119 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809119 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809119"> <li> <div class="comment"> <table class="comment-table" commentId="809124" commentParentId="809119"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809124" href="?#comment-809124" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809119" style="font-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="809124" 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="809124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809124"> <div class="moveup"> <div class="ttypography"><p>My solution is simple. First sort the array. </p><p>Then start connecting adjacent values with their differences. This way sum of all edges with positive weight will be same as the sum of adjacent differences in the array.</p><p>After that start making negative edges for every i. So each i will have i negative edges. Where negative weight is same as -(arr[i] — arr[j]).</p><p>Instead of search it for every j I have formula as (prefixsum till i) — arr[i]*i</p></div> </div> </div> <div class="reply info"> <a class="comment-809124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809124"> <li> <div class="comment"> <table class="comment-table" commentId="809132" commentParentId="809124"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809132" href="?#comment-809132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809124" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809132"> <div class="moveup"> <div class="ttypography"><p>can you tell me why are we sorting the array for a particular node call it x we need to add a negative weight from x to 1 , x to 2 x to 3 till x to x-1 keeping in mind the the path sum doesn't become negative so why are we sorting the array</p></div> </div> </div> <div class="reply info"> <a class="comment-809132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809132"> <li> <div class="comment"> <table class="comment-table" commentId="809135" commentParentId="809132"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809135" href="?#comment-809135" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809135" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809135"> <div class="moveup"> <div class="ttypography"><p>We are sorting values only once so as to connect neighboring nodes with minimum values,i.e. difference b/w consecutive values.<br /> From this sum of positive edges will be minimum.</p></div> </div> </div> <div class="reply info"> <a class="comment-809135 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809135 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809135"> <li> <div class="comment"> <table class="comment-table" commentId="809139" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809139" href="?#comment-809139" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809139" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809139"> <div class="moveup"> <div class="ttypography"><p>ohhh thanks I got it</p></div> </div> </div> <div class="reply info"> <a class="comment-809139 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809139 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809139"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809145" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809145" href="?#comment-809145" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809145" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809145"> <div class="moveup"> <div class="ttypography"><p>My solution is working now I only needed to sort the array my code would have been accepted during the contest :(</p></div> </div> </div> <div class="reply info"> <a class="comment-809145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809145"> </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="809116" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ken_KaNeKi_997" style="position: relative;"> <img src='https://userpic.codeforces.org/1737228/avatar/50ceb845253df5d4.jpg'/> </a> <div><a href="/profile/Ken_KaNeKi_997" title="Newbie Ken_KaNeKi_997" class="rated-user user-gray">Ken_KaNeKi_997</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809116" href="?#comment-809116" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809116" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1737228" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809116"> <div class="moveup"> <div class="ttypography"><p>can anyone explain div2 B plz</p></div> </div> </div> <div class="reply info"> <a class="comment-809116 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809116 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809116"> <li> <div class="comment"> <table class="comment-table" commentId="809204" commentParentId="809116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809204" href="?#comment-809204" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809116" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809204" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809204"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/92199#comment-809178">here</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809204 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809204 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809204"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809122" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809122" href="?#comment-809122" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809122" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809122"> <div class="moveup"> <div class="ttypography"><p>Beautiful Problems. Amazing Round!!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-809122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809122"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809156" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dummybawa" style="position: relative;"> <img src='https://userpic.codeforces.org/1704408/avatar/1522f670cd21321.jpg'/> </a> <div><a href="/profile/dummybawa" title="Expert dummybawa" class="rated-user user-blue">dummybawa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809156" href="?#comment-809156" style="font-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="809156" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809156" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1704408" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809156"> <div class="moveup"> <div class="ttypography"><p>UPD: It's wrong. </p></div> </div> </div> <div class="reply info"> <a class="comment-809156 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809156 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809156"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809178" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809178" href="?#comment-809178" style="font-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="809178" 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="809178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809178"> <div class="moveup"> <div class="ttypography"><p>For DIV 2C/1A can anyone explain with this test case N = 6 and D = 0 1 2 3 2 3. What are the edges that we can have with their weights?</p></div> </div> </div> <div class="reply info"> <a class="comment-809178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809178"> <li> <div class="comment"> <table class="comment-table" commentId="809198" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Zemrith" style="position: relative;"> <img src='https://userpic.codeforces.org/1159882/avatar/2a6566e372882267.jpg'/> </a> <div><a href="/profile/Zemrith" title="Expert Zemrith" class="rated-user user-blue">Zemrith</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809198" href="?#comment-809198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-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="809198" 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="809198" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159882" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809198"> <div class="moveup"> <div class="ttypography"><p>Hello! The answer would be -18.</p><p>Diagram: <img alt=" " src="/predownloaded/8c/88/8c88a0230dea9f499896ee59def659611c605976.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Notice that once you sort the distances, the adjacent nodes have no effect on your final answer. But you can add negative edges as long as they are not adjacent, resulting in such a diagram. Hence you can use prefix sums to solve the problem. (if x nodes came before this, for each node, the answer to add is (x-1)*curr value — csum of first (x-1) nodes). </p><p>Hope that made sense!</p></div> </div> </div> <div class="reply info"> <a class="comment-809198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809198"> <li> <div class="comment"> <table class="comment-table" commentId="809218" commentParentId="809198"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:27">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809218" href="?#comment-809218" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809218" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809218"> <div class="moveup"> <div class="ttypography"><p>Thank you <a class="rated-user user-cyan" href="/profile/Zemrith" title="Специалист Zemrith">Zemrith</a> for so much detail explanation and the solution too it helped me a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-809218 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809218 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809218"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809199" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809199" href="?#comment-809199" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809199" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809199"> <div class="moveup"> <div class="ttypography"><p>first sort the array they will from non negative weight edges. 0 -&gt; 1 -&gt; 2 -&gt; 2 -&gt; 3 -&gt; 3 so the non negative weights will be 1 | 1 | 0 | 1 | 0. form here greedily build most negative weights(backward edges) such that there are no negative cycles.</p></div> </div> </div> <div class="reply info"> <a class="comment-809199 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809199 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809199"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809203" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809203" href="?#comment-809203" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809203" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809203"> <div class="moveup"> <div class="ttypography"><p>First you can sort D and get: <code> N = 6, D = [0, 1, 2, 2, 3, 3] </code></p><p>Now calculate the diffs:</p><p><code>diffs = [1, 1, 0, 1, 0]</code></p><p>The edges for this graph could be something like this:</p> <pre><code> 1 1 0 1 0 &lt;- forward edges 1 &lt;-&gt; 2 &lt;-&gt; 3 &lt;-&gt; 4 &lt;-&gt; 5 &lt;-&gt; 6 -1 -1 0 -1 0 &lt;- backward edges </code></pre><p>Now you have to add more negatives edges, and you could do this by choosing some <code>i</code> and <code>j</code>, <code>i &lt; j</code> and add an edges from <code>j</code> to <code>i</code>, and the weight will be sum of the values from <code>diff[i]</code> to <code>diff[j]</code>.</p><p>Another way to think about this is: look at <code>D</code> array, it represents distances between adjacent nodes, all we have to do is add all of the edges with length 2, then all of the edges of length 3, ..., all of the edges of length <code>N - 1</code>.</p><p>So, for our case we would have these edges</p> <pre><code>a b W ------- 1 2 - 1 2 3 - 1 3 4 - 0 &lt;- adjacent forward edges 4 5 - 1 5 6 - 0 2 1 - -1 3 2 - -1 4 3 - 0 &lt;- adjacent backward edges 5 4 - -1 6 5 - 0 3 1 - -2 4 2 - -1 5 3 - -1 &lt;- edges of length 2 6 4 - -1 4 1 - -2 5 2 - -2 &lt;- edges of length 3 6 3 - -1 5 1 - -3 6 2 - -2 &lt;- edges of length 4 6 1 - -3 &lt;- edges of length 5 </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809203 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809203 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809203"> <li> <div class="comment"> <table class="comment-table" commentId="809221" commentParentId="809203"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809221" href="?#comment-809221" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809203" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809221" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809221"> <div class="moveup"> <div class="ttypography"><p>Thank You <a class="rated-user user-green" href="/profile/ilidar" title="Ученик ilidar">ilidar</a> for clearing my doubt and for detailed explaination.</p></div> </div> </div> <div class="reply info"> <a class="comment-809221 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809221 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809221"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809280" href="?#comment-809280" style="font-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="809280" revisionCount="7" revision="7"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">7</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809280" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+18</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809280"> <div class="moveup"> <div class="ttypography"><p>Could someone please provide a more strict intuition or insight of Div2D/Div1B of why &quot;the actual probability p does not matter&quot;? The intuition in the editorial is still alien to me of why those choices of not progess toward to either stacks (and probability 'p' also changes from time to time too) doesn't matter.</p><p>Update: Here is the intuition I came up with (The strict proof can be found in the comment of the author below)</p><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left) in some states of the current tree.</p><p>now, we will try break this $$$dp_{i,j}$$$ down into the sum of $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$</p><p>We will try to illustrate this with trying to split and color, either red or blue, a stick of length $$$1$$$. The length of the sticks representing the 'probability', and the color of the sticks will represent $$$dp_{i-1,j}$$$(red) or $$$dp_{i,j-1}$$$(blue), depending on the color.</p><p>Suppose in the current state, we have probability $$$p$$$ for choosing to pop each stacks, and the rest $$$1-2p$$$ of doing nothing. The picture will look like this:</p><p><a href="https://ibb.co/q9HjQTm"><img alt="Tree-Array-Rep" border="0" src="/predownloaded/13/57/135732d2b0967af0f76c1dba28df72086f234c7d.png" style="max-width: 100.0%;max-height: 100.0%;" /></a></p><p>We will split the stick equally(*) into several sticks of length $$$p$$$, and then color two of them red and blue. (* We can split it evenly because in the original problem, $$$p$$$ is in the form $$$\frac{1}{number\ of\ candidate\ unmark\ nodes}$$$ ) Now, the remaining sticks represent the state of $$$dp_{i,j}$$$ again (in some other state of the entire tree, so might be in some different $$$p$$$). That means we will split those sticks similary.</p><p>The key observations is:</p><p>1) We know that, in the original problem, if we keep picking nodes that aren't progressing toward the target nodes, we will run out of nodes eventually and finally choose the two nodes. That means, all the sticks will eventually colored into 'red' and 'blue'.</p><p>2) When we split a stick into several smaller equal length sticks, we will color two of them into red and blue. <strong>Those two sticks always have the same length</strong>. That means, the total length of blue sticks and the total length of red sticks will be equal in the end.</p><p>Analogically, that means, eventually, $$$dp_{i,j}$$$ will split into $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$ evenly, no matter $$$p$$$ might be or the state of tree of $$$dp_{i,j}$$$ might be. Therefore, $$$dp_{i,j} = \frac{1}{2} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-809280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809280"> <li> <div class="comment"> <table class="comment-table" commentId="809284" commentParentId="809280"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809284" href="?#comment-809284" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809280" style="font-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="809284" 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="809284" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809284"> <div class="moveup"> <div class="ttypography"><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left), with having arbitary probability $$$0 &lt; p \leq 0.5$$$ of chosing to pick the top of each stack (and $$$1-2p$$$ for doing nothing). Then</p><p>$$$dp_{i,j}=\int_{0}^{0.5} x \cdot (dp_{i-1,j}+dp_{i,j-1}) + (1-2x) \cdot dp_{i,j} \,dx$$$</p><p>Solving the equation, we get $$$dp_{i,j}=\frac{1}{6} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$ What is the mistake in this logic?</p></div> </div> </div> <div class="reply info"> <a class="comment-809284 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809284 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809284"> <li> <div class="comment"> <table class="comment-table" commentId="809399" commentParentId="809284"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809399" href="?#comment-809399" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809284" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809399" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809399"> <div class="moveup"> <div class="ttypography"><p>The biggest issue with this logic is that it's assuming $$$p$$$ is arbitrary chosen from a certain state. While $$$p$$$ can be anything in the world, it is always an exact number from a certain state, hence why an integral is wrong. </p><p>As a different type of intuition, you can think, &quot;is it more likely to reach $$$(i-1, j)$$$ than state $$$(i, j-1)$$$&quot;? and vice versa. For me at least, I don't see how it's possible for either of those questions to be true, so they should be equal.</p><p>If you're looking for a more rigorously correct $$$dp$$$, it would look something like this.</p> <div class="spoiler"><b class="spoiler-title">Proof</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp_{i, j, S}$$$ denote the probability of reaching some node $$$i$$$ distance away before some node $$$j$$$ distance away where $$$S$$$ is a representation of the entire state of of the process (not necessarily an integer). I think you already understood why we can assume the $$$lca$$$ is already reached. We aim to show that $$$S$$$ does not matter in our calculation. Assume inductively that $$$S$$$ does not matter. So, we can assume that states $$$(i-1, j)$$$ and states $$$(i, j-1)$$$ are irrelevant to $$$S$$$. Hence, the part we need to care about is $$$(1-2p) dp_{i, j, S \rightarrow S_a}$$$. A way of thinking about this part of the transition is moving through the collection of $$$S$$$ with the state $$$(i, j)$$$. Obviously, the $$$dp$$$ is a $$$DAG$$$ because no state $$$S$$$ can reach another. Each bounce takes a certain probability $$$p$$$ which is just multiplied in the current path. So, for each state $$$S$$$ with state $$$(i, j)$$$, we have a certain probability to reach it by simply calculating $$$dp$$$ along a DAG as is traditional. Then, from those states of $$$(i, j)$$$ you transition to $$$(i, j-1)$$$ with an equal probability $$$(i-1, j)$$$. So, they have to be equal. Finally, this argument holds for any initial state $$$S$$$ that you reach, so we can conclude that, from any state $$$S$$$ with a state of $$$(i, j)$$$, the probability of transitions to $$$(i-1, j)$$$ and $$$(i, j-1)$$$ are always exactly $$$0.5$$$.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-809399 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809399 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809399"> <li> <div class="comment"> <table class="comment-table" commentId="809701" commentParentId="809399"> <tr> <td class="left"> <div style="position: absolute; left: 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/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809701" href="?#comment-809701" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809399" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809701" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809701"> <div class="moveup"> <div class="ttypography"><p>I see, thank you so much!</p></div> </div> </div> <div class="reply info"> <a class="comment-809701 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809701 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809701"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809298" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/satyam_singh93" style="position: relative;"> <img src='https://userpic.codeforces.org/1763011/avatar/9d9fa405de19ab0e.jpg'/> </a> <div><a href="/profile/satyam_singh93" title="Newbie satyam_singh93" class="rated-user user-gray">satyam_singh93</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809298" href="?#comment-809298" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809298" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1763011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809298"> <div class="moveup"> <div class="ttypography"><p>I am getting wrong ans . could someone tell me where the code make differene ( [yestrday competiton problem .</p><p>`](<a href="https://codeforces.com/contest/1541/problem/B)">https://codeforces.com/contest/1541/problem/B)</a>.</p> <pre><code>int main( ) { clock_t begin = clock(); file_i_o(); // Write your code here.... int t; cin&gt;&gt;t; while(t-- ){ int n; cin&gt;&gt;n; vector&lt;pair&lt;int,int&gt;&gt;v; v.push_back({0,0}); loop(i,0,n) { int x; cin&gt;&gt;x; v.pb({x,i+1}); } sort(v.begin()+1,v.end()); int count =0; for(int i=1 ; i&lt;=n;i++) { for(ll j=i+1;j&lt;=n;j++) { ll left = v[i].first * v[j].first; ll right = v[i].second + v[j].second; if(left == right) count++; if(left &gt; 2*n ) break; } } cout&lt;&lt;count&lt;&lt;endl; } </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809298 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809298 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809298"> <li> <div class="comment"> <table class="comment-table" commentId="809305" commentParentId="809298"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809305" href="?#comment-809305" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809298" style="font-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="809305" 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="809305" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809305"> <div class="moveup"> <div class="ttypography"><p>v[i].first * v[j].first can create overflow. So, you need to convert them to long long by using</p><p>ll left = 1LL * v[i].first * v[j].first;</p><p>instead and it would pass.</p><p>(Simply save the value in long long won't help. You need to convert them to long long before doing multiplication. 1LL* is one way)</p></div> </div> </div> <div class="reply info"> <a class="comment-809305 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809305 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809305"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809309" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809309" href="?#comment-809309" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809309" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809309"> <div class="moveup"> <div class="ttypography"><p>Hi, in problem Div1.B/Div2.D; I can't wrap my head around $$$F[x][y]=F[x−1][y]/2+F[x][y−1]/2$$$. Why is it not $$$F[x][y]=F[x−1][y+1]/2+F[x+1][y−1]/2$$$, can someone please explain to me why is my transition wrong and/or why is the aforementioned transition correct? </p></div> </div> </div> <div class="reply info"> <a class="comment-809309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809309"> <li> <div class="comment"> <table class="comment-table" commentId="809311" commentParentId="809309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809311" href="?#comment-809311" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809311" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809311"> <div class="moveup"> <div class="ttypography"><p>x and y is the distance left for each side right? So, if you take one out, it won't make sense to add that one to the other side since the distance should be either x-1 and y or x and y-1.</p></div> </div> </div> <div class="reply info"> <a class="comment-809311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809311"> <li> <div class="comment"> <table class="comment-table" commentId="809339" commentParentId="809311"> <tr> <td class="left"> <div style="position: absolute; left: 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/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809339" href="?#comment-809339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809339" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809339"> <div class="moveup"> <div class="ttypography"><p>Thank you so much I understand. I had a minor misunderstanding of the parameters to the dp state.</p></div> </div> </div> <div class="reply info"> <a class="comment-809339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809339"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809371" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:13">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809371" href="?#comment-809371" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809371" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809371"> <div class="moveup"> <div class="ttypography"><p>PLease explain why 2 same codes are not giving the same ans</p><p>code forces round 728 div2<br />Problem B :<a href="https://codeforces.com/contest/1541/problem/B">https://codeforces.com/contest/1541/problem/B</a></p><p>AC Submission : <a href="https://ide.codingblocks.com/s/579769">https://ide.codingblocks.com/s/579769</a></p><p>Wrong output Submission :<a href="https://ide.codingblocks.com/s/579771">https://ide.codingblocks.com/s/579771</a></p><p>Difference is using of macro (node) instead of pair&lt;int,int&gt; </p><p>Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-809371 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809371 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809371"> <li> <div class="comment"> <table class="comment-table" commentId="809379" commentParentId="809371"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809379" href="?#comment-809379" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809371" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809379" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809379"> <div class="moveup"> <div class="ttypography"><p>If i am using #define node pair&lt;int,int&gt; it is getting accepted but when i am using typedef pair&lt;int,int&gt; node; it is giving wrong answer</p><p>Why this is happening ?? Is it a bug??</p></div> </div> </div> <div class="reply info"> <a class="comment-809379 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809379 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809379"> <li> <div class="comment"> <table class="comment-table" commentId="809407" commentParentId="809379"> <tr> <td class="left"> <div style="position: absolute; left: 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/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 19:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809407" href="?#comment-809407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809379" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809407" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809407"> <div class="moveup"> <div class="ttypography"><p>Not really sure why this is happening.</p><p>However, I think the problem is the position of #define int long long. So, for #define pair&lt;int,int&gt; node it seems that compiler change node -&gt; pair&lt;int,int&gt; -&gt; pair&lt;long long, long long&gt;. However, when you do typedef, it still keeps in pair&lt;int, int&gt; which creates an overflow problem later on. </p><p>I did try moving #define int long long up above typedef and the code pass. So, my best guess is #define int long long only replace int after that position with long long. Thus, node is still pair&lt;int, int&gt; in the typedef solution, while node is changed to pair&lt;long long, long long&gt; in the second solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-809407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809407"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809627" href="?#comment-809627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809627"> <div class="moveup"> <div class="ttypography"><p>May I ask why in the Div1D solution ci=i-bi, I think it should be ci=bi ...</p></div> </div> </div> <div class="reply info"> <a class="comment-809627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809627"> <li> <div class="comment"> <table class="comment-table" commentId="809631" commentParentId="809627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809631" href="?#comment-809631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809631" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809631"> <div class="moveup"> <div class="ttypography"><p>Check the definition of bi again dude. bi here means <strong>number of elements greater than pi</strong>. So to get ci, which is <strong>number of elements smaller than pi</strong>, you need i-bi.</p></div> </div> </div> <div class="reply info"> <a class="comment-809631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809631"> <li> <div class="comment"> <table class="comment-table" commentId="809636" commentParentId="809631"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809636" href="?#comment-809636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809636"> <div class="moveup"> <div class="ttypography"><p>I read it again. If I read it correctly, bi stands for j&lt;i,pj&gt;pi, and ci stands for j&gt;i,pj&lt;pi. For example, p={1,3,5,4,6,2}, I think b4=1,c4=1, please point out my problem</p></div> </div> </div> <div class="reply info"> <a class="comment-809636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809636"> <li> <div class="comment"> <table class="comment-table" commentId="809638" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809638" href="?#comment-809638" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809638" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809638"> <div class="moveup"> <div class="ttypography"><p>oh, the array index starts from 1</p></div> </div> </div> <div class="reply info"> <a class="comment-809638 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809638 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809638"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809639" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809639" href="?#comment-809639" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809639" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809639"> <div class="moveup"> <div class="ttypography"><p>You are right.</p><p>I guess it might just be typo and ci stands for j&lt;i, pj&lt;pi. At least with this definition of ci the algorithm seems correct :)</p></div> </div> </div> <div class="reply info"> <a class="comment-809639 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809639 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809639"> <li> <div class="comment"> <table class="comment-table" commentId="809641" commentParentId="809639"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809641" href="?#comment-809641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809639" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809641"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-809641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809641"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809705" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/darthrevenge" style="position: relative;"> <img src='https://userpic.codeforces.org/1567000/avatar/ee31d2a91a9575b9.jpg'/> </a> <div><a href="/profile/darthrevenge" title="Candidate Master darthrevenge" class="rated-user user-violet">darthrevenge</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809705" href="?#comment-809705" style="font-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="809705" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809705" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1567000" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809705"> <div class="moveup"> <div class="ttypography"><p>Here's my solution of B div 1 / D div 2 without LCA, using single DFS per node. <a href="/contest/1540/submission/120700765" title="Посылка 120700765 от darthrevenge">120700765</a> It is similar to what <a class="rated-user user-violet" href="/profile/OleschY" title="Кандидат в мастера OleschY">OleschY</a> suggested above. I've tried to describe it in the <a href="https://codeforces.com/blog/entry/92284">blog</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-809705 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809705 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809705"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809951" href="?#comment-809951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809951"> <div class="moveup"> <div class="ttypography"><p>Can someone explain how you can find the LCA for each pair so quick? Iterating through every root is and then considering every pair is already N^3</p></div> </div> </div> <div class="reply info"> <a class="comment-809951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809951"> <li> <div class="comment"> <table class="comment-table" commentId="809965" commentParentId="809951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PurpleCrayon" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809965" href="?#comment-809965" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809965" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="1604355" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809965"> <div class="moveup"> <div class="ttypography"><p>There are a couple ways you could do it:</p> <ol> <li>Just use standard binary lifting (initialize once for each root). This runs in $$$\mathcal{O}(n^3 \log{}n)$$$, and should pass under the given constraints. You could also just use $$$\mathcal{O}(1)$$$ lca using an rmq over an euler tour.</li> <li>You could use a version of dp, where $$$dp[a][b] = lca(a, b)$$$. If the depth of $$$a$$$ is greater than the depth of $$$b$$$, $$$dp[a][b] = dp[parent[a]][b]$$$, otherwise $$$dp[a][b] = dp[a][parent[b]]$$$. The base cases are $$$dp[a][a] = a$$$ for all $$$a$$$. This runs in $$$\mathcal{O}(n^3)$$$.</li> <li>You could extend this idea and do the main solution's dp directly on the tree (without ever worrying about lca's). The recurrence is equivalent to the main solution ($$$dp[a][b] = \frac{dp[parent[a]][b]+dp[a][parent[b]]}{2}$$$ with the base cases being one node is an ancestor of the other.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-809965 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809965 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809965"> <li> <div class="comment"> <table class="comment-table" commentId="809967" commentParentId="809965"> <tr> <td class="left"> <div style="position: absolute; left: 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/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809967" href="?#comment-809967" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809965" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809967" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809967"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the detailed answer!</p></div> </div> </div> <div class="reply info"> <a class="comment-809967 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809967 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809967"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="810320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Anurag_20" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Anurag_20" title="Specialist Anurag_20" class="rated-user user-cyan">Anurag_20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/30/2021 19:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810320" href="?#comment-810320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810320" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1600346" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810320"> <div class="moveup"> <div class="ttypography"><p>O(n2) is also working for div2 C Great Graphs. <a href="https://codeforces.com/contest/1540/submission/120964787">https://codeforces.com/contest/1540/submission/120964787</a></p></div> </div> </div> <div class="reply info"> <a class="comment-810320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810320"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="813828" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/T404" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/T404" title="Master T404" class="rated-user user-orange">T404</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/09/2021 19:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-813828" href="?#comment-813828" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="813828" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="523287" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-813828"> <div class="moveup"> <div class="ttypography"><p>Div1D can be done in $$$O(n \sqrt{n})$$$. We can use square root decomposition to replace all BITs in tutorial. Since a value in a non-updated position changes by at most one and all values change in the same direction, the full recomputation is only needed in the updated position and we can perform an incremental change in $$$O(1)$$$ for values in each non-updated positions.</p><p><a href="https://codeforces.com/contest/1540/submission/121831547">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-813828 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-813828 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-813828"> <li> <div class="comment"> <table class="comment-table" commentId="834051" commentParentId="813828"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KeyID" style="position: relative;"> <img src='https://userpic.codeforces.org/226684/avatar/10e3671716bf6859.jpg'/> </a> <div><a href="/profile/KeyID" title="Grandmaster KeyID" class="rated-user user-red">KeyID</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/29/2021 12:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-834051" href="?#comment-834051" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-813828" style="font-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="834051" 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="834051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="226684" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-834051"> <div class="moveup"> <div class="ttypography"><p>Realy impressive solution. I'm surprised no stars were given to you until me. Maybe many people didn't get your idea since the solution is actually much more complicated than your brief comment(at least in my opinion). I also wrote a piece of code which used your method but simplified a small part of steps. <a href="https://codeforces.com/contest/1540/submission/127317031">Here</a> it is.</p></div> </div> </div> <div class="reply info"> <a class="comment-834051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-834051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-834051"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="837924" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Harolinch" style="position: relative;"> <img src='https://userpic.codeforces.org/427341/avatar/cf8608aeb55edc95.jpg'/> </a> <div><a href="/profile/Harolinch" title="Pupil Harolinch" class="rated-user user-green">Harolinch</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837924" href="?#comment-837924" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837924" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="427341" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837924"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a> in problem Tree array you said that Fixing a given root r, the expected value of the entire process is obviously the sum of the expected values for a fixed root divided by n.</p><p>why we divide by n at the end ? </p></div> </div> </div> <div class="reply info"> <a class="comment-837924 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837924 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837924"> <li> <div class="comment"> <table class="comment-table" commentId="837928" commentParentId="837924"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837928" href="?#comment-837928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-837924" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837928" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837928"> <div class="moveup"> <div class="ttypography"><p>The calculation is independent based on whichever node that you choose first (it becomes the “root”). Initially you choose one of $$$n$$$ nodes with equal probability so you divide by $$$n$$$ at the end after you’ve summed up the independent expected value after choosing the node $$$i$$$ initially.</p></div> </div> </div> <div class="reply info"> <a class="comment-837928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837928"> </ul> </div> </li> </ul> </div> <br/> <div id="editBox-100805" 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 firstPreview100805 = true; var lastPreviewContent100805 = ''; 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=100805] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=100805] 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-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, 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:33:28</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:'81289372dffb0c4e',t:'MTY5NjcwNzIwOC45MzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1541E2
1541
E2
ru
E2. Сходящийся массив (сложная версия)
<div class="problem-statement"><div class="header"><div class="title">E2. Сходящийся массив (сложная версия)</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-bf">Это — усложненная версия задачи. Единственное различие в том, что в данной версии $$$1 \le q \le 10^5$$$. Вы можете взламывать другие решения, только если решены обе версии задачи.</span></p><p>Рассмотрим процесс, проходящий на массивах $$$a$$$ и $$$b$$$ длины $$$n$$$ и $$$n-1$$$ соответственно. </p><p>Процесс — это бесконечная последовательность действий. Каждое действие имеет следующий вид: </p><ul> <li> Сначала, выберем случайное целое число $$$i$$$ ($$$1 \le i \le n-1$$$). </li><li> Теперь, одновременно присвоим $$$a_i = \min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right)$$$ и $$$a_{i+1} = \max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right)$$$ без округлений (то есть значения могут перестать быть целыми). </li></ul> Пример такой операции представлен в заметках.<p>Можно доказать, что массив $$$a$$$ сходится, т. е. для каждого $$$i$$$ существует предел, к которому $$$a_i$$$ сходится. Пусть функция $$$F(a, b)$$$ возвращает значение, к которому сходится $$$a_1$$$, в результате процесса на массивах $$$a$$$ и $$$b$$$.</p><p>Вам задан массив $$$b$$$, но не массив $$$a$$$. Однако вам задан третий массив $$$c$$$. Назовем массив $$$a$$$ хорошим, если он состоит из <span class="tex-font-style-bf">целых чисел</span> и удовлетворяет неравенству $$$0 \leq a_i \leq c_i$$$ для всех $$$1 \leq i \leq n$$$.</p><p>Ваша задача — посчитать количество хороших массивов $$$a$$$, для которых $$$F(a, b) \geq x$$$, для $$$q$$$ значений $$$x$$$. Так как ответ может быть слишком большим, выведите его по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$2 \le n \le 100$$$).</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$c_1, c_2 \ldots, c_n$$$ ($$$0 \le c_i \le 100$$$).</p><p>В третьей строке заданы $$$n-1$$$ целых чисел $$$b_1, b_2, \ldots, b_{n-1}$$$ ($$$0 \le b_i \le 100$$$).</p><p>В четвертой строке задано одно целое число $$$q$$$ ($$$1 \le q \le 10^5$$$).</p><p>В пятой строке заданы $$$q$$$ целых чисел $$$x_1, x_2, \ldots, x_q$$$ ($$$-10^5 \le x_i \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ целых чисел, где $$$i$$$-е число — ответ на $$$i$$$-й запрос, т. е. количество хороших массивов $$$a$$$ с $$$F(a, b) \geq x_i$$$ по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 3 4 2 1 5 -1 0 1 -100000 100000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 56 28 4 60 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Объяснение далее предполагает, что $$$b = [2, 1]$$$ и $$$c=[2, 3, 4]$$$ (как в примере).</p><p>Примеры массивов $$$a$$$, которые <span class="tex-font-style-bf">не</span> являются хорошими: </p><ul> <li> $$$a = [3, 2, 3]$$$ не является хорошим, потому что $$$a_1 &gt; c_1$$$; </li><li> $$$a = [0, -1, 3]$$$ не является хорошим, потому что $$$a_2 &lt; 0$$$. </li></ul><p>Один из возможных хороших массивов $$$a$$$ — это $$$[0, 2, 4]$$$. Можно показать, что ни одна операция его не изменит, а потому $$$F(a, b) = a_1 = 0$$$.</p><p>Другой возможных хороший массив $$$a$$$ — это $$$[0, 1, 4]$$$. За одну операцию с $$$i = 1$$$ мы присваиваем $$$a_1 = \min(\frac{0+1-2}{2}, 0)$$$ и $$$a_2 = \max(\frac{0+1+2}{2}, 1)$$$. То есть, после одной операции с $$$i = 1$$$, $$$a$$$ становится равен $$$[-\frac{1}{2}, \frac{3}{2}, 4]$$$. Можно показать, что далее ни одна операция не изменит массив, а потому $$$F(a, b) = -\frac{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="20738b3b456e4fc66b72f764d4435155"/> <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="3a2e30eec6604291efb1f3ef212d19e2d7715bd7"/> <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='20738b3b456e4fc66b72f764d4435155'>&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%2F1541%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='20738b3b456e4fc66b72f764d4435155'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1541">Codeforces Round 728 (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='20738b3b456e4fc66b72f764d4435155'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1541/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='20738b3b456e4fc66b72f764d4435155'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1027097"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='20738b3b456e4fc66b72f764d4435155'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1027097"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92093" title="Codeforces Round #728" target="_blank">Codeforces Round #728 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13929" resourceName="Codeforces Round #728" resourceManual="true" src="//codeforces.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/92199" title="Tutorial" target="_blank">Tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13941" 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/1541">Задачи</a></li> <li><a href="/contest/1541/submit">Отослать</a></li> <li><a href="/contest/1541/my">Мои посылки</a></li> <li><a href="/contest/1541/status">Статус</a></li> <li><a href="/contest/1541/hacks">Взломы</a></li> <li><a href="/contest/1541/room/1">Комната</a></li> <li><a href="/contest/1541/standings">Положение</a></li> <li><a href="/contest/1541/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_ab74c629434e0d3ed348593c630d762bfe296263"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это — усложненная версия задачи. Единственное различие в том, что в данной версии $$$1 \le q \le 10^5$$$. Вы можете взламывать другие решения, только если решены обе версии задачи.</span></p><p>Рассмотрим процесс, проходящий на массивах $$$a$$$ и $$$b$$$ длины $$$n$$$ и $$$n-1$$$ соответственно. </p><p>Процесс — это бесконечная последовательность действий. Каждое действие имеет следующий вид: </p><ul> <li> Сначала, выберем случайное целое число $$$i$$$ ($$$1 \le i \le n-1$$$). </li><li> Теперь, одновременно присвоим $$$a_i = \min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right)$$$ и $$$a_{i+1} = \max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right)$$$ без округлений (то есть значения могут перестать быть целыми). </li></ul> Пример такой операции представлен в заметках.<p>Можно доказать, что массив $$$a$$$ сходится, т. е. для каждого $$$i$$$ существует предел, к которому $$$a_i$$$ сходится. Пусть функция $$$F(a, b)$$$ возвращает значение, к которому сходится $$$a_1$$$, в результате процесса на массивах $$$a$$$ и $$$b$$$.</p><p>Вам задан массив $$$b$$$, но не массив $$$a$$$. Однако вам задан третий массив $$$c$$$. Назовем массив $$$a$$$ хорошим, если он состоит из <span class="tex-font-style-bf">целых чисел</span> и удовлетворяет неравенству $$$0 \leq a_i \leq c_i$$$ для всех $$$1 \leq i \leq n$$$.</p><p>Ваша задача — посчитать количество хороших массивов $$$a$$$, для которых $$$F(a, b) \geq x$$$, для $$$q$$$ значений $$$x$$$. Так как ответ может быть слишком большим, выведите его по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$2 \le n \le 100$$$).</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$c_1, c_2 \ldots, c_n$$$ ($$$0 \le c_i \le 100$$$).</p><p>В третьей строке заданы $$$n-1$$$ целых чисел $$$b_1, b_2, \ldots, b_{n-1}$$$ ($$$0 \le b_i \le 100$$$).</p><p>В четвертой строке задано одно целое число $$$q$$$ ($$$1 \le q \le 10^5$$$).</p><p>В пятой строке заданы $$$q$$$ целых чисел $$$x_1, x_2, \ldots, x_q$$$ ($$$-10^5 \le x_i \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ целых чисел, где $$$i$$$-е число — ответ на $$$i$$$-й запрос, т. е. количество хороших массивов $$$a$$$ с $$$F(a, b) \geq x_i$$$ по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 3 4 2 1 5 -1 0 1 -100000 100000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 56 28 4 60 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Объяснение далее предполагает, что $$$b = [2, 1]$$$ и $$$c=[2, 3, 4]$$$ (как в примере).</p><p>Примеры массивов $$$a$$$, которые <span class="tex-font-style-bf">не</span> являются хорошими: </p><ul> <li> $$$a = [3, 2, 3]$$$ не является хорошим, потому что $$$a_1 &gt; c_1$$$; </li><li> $$$a = [0, -1, 3]$$$ не является хорошим, потому что $$$a_2 &lt; 0$$$. </li></ul><p>Один из возможных хороших массивов $$$a$$$ — это $$$[0, 2, 4]$$$. Можно показать, что ни одна операция его не изменит, а потому $$$F(a, b) = a_1 = 0$$$.</p><p>Другой возможных хороший массив $$$a$$$ — это $$$[0, 1, 4]$$$. За одну операцию с $$$i = 1$$$ мы присваиваем $$$a_1 = \min(\frac{0+1-2}{2}, 0)$$$ и $$$a_2 = \max(\frac{0+1+2}{2}, 1)$$$. То есть, после одной операции с $$$i = 1$$$, $$$a$$$ становится равен $$$[-\frac{1}{2}, \frac{3}{2}, 4]$$$. Можно показать, что далее ни одна операция не изменит массив, а потому $$$F(a, b) = -\frac{1}{2}$$$.</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 11:29: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:'8124c71bd8cf9d70',t:'MTY5NjY2NzM4MS4yMDUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*2900"]
https://codeforces.com/blog/entry/92199
<!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="ea33d124a1ff874ace73f937748d303e"/> <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="Codeforces Round #728 Editorial - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Codeforces Round #728 Editorial - Codeforces</title> <meta name="description" content="Codeforces. Programming competitions and contests, programming community" /> <meta name="keywords" content="programming algorithm contest competition informatics olympiads c++ java graphs vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/font-awesome.min.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/line-awesome.min.css" type="text/css" charset="utf-8" /> <link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/81027/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/81027/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/81027/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/81027/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/81027/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/81027/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/81027/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/81027/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/81027/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/81027/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/81027/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/81027/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/81027/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="//codeforces.org/s/81027/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!--CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/css/prettify.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/clear.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/ttypography.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/problem-statement.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/second-level-menu.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/roundbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/datatable.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/table-form.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/topic.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.jgrowl.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/facebox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.autocomplete.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/codeforces.datepick.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/colorbox.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/jquery.drafts.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/community.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/javascript" async src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full" > </script> <!-- /MathJax --> <script type="text/javascript" src="//codeforces.org/s/81027/js/prettify/prettify.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/moment-with-locales.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/pushstream.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.easing.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.lavalamp.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.jgrowl.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.swipe.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.hotkeys.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/facebox.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.wysiwyg.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.colorpicker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.table.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.image.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/controls/wysiwyg.link.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.autocomplete.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ie6blocker.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.ba-bbq.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.drafts.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/clipboard.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/autosize.min.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/sjcl.js"></script> <script type="text/javascript" src="/scripts/573cedc6b04c15481941f418269f4057/en/codeforces-options.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/codeforces.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/EventCatcher.js?v=20160131"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/preparedVerdictFormats-en.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/js/confetti.min.js"></script> <!--/CombineResourcesFilter--> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" /> <link rel="stylesheet" href="//codeforces.org/s/81027/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" /> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/jquery.markitup.js"></script> <script type="text/javascript" src="//codeforces.org/s/81027/markitup/sets/markdown/set.js"></script> <!--[if IE]> <style> #sidebar { padding-left: 1em; margin: 1em 1em 1em 0; } </style> <![endif]--> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='ea33d124a1ff874ace73f937748d303e'>&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%2F92199">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='ea33d124a1ff874ace73f937748d303e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:31:32</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:31:32</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='ea33d124a1ff874ace73f937748d303e'/> <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/PurpleCrayon">PurpleCrayon</a></li> <li class="current selectedLava"><a href="/blog/PurpleCrayon">Blog</a></li> <li><a href="/teams/with/PurpleCrayon">Teams</a></li> <li><a href="/submissions/PurpleCrayon">Submissions</a></li> <li><a href="/groups/with/PurpleCrayon">Groups</a></li> <li><a href="/contests/with/PurpleCrayon">Contests</a></li> <li><a href="/contests/writer/PurpleCrayon">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/PurpleCrayon" style="text-decoration:none;color:black !important;">PurpleCrayon's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="92809"> <div class="title"> <a href="/blog/entry/92199"> <p>Codeforces Round #728 Editorial</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a>, <a href="/topic/92809/en10">history</a>, <span class="format-humantime" title="Jun/25/2021 20:44">2 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><a href="/contest/1541/problem/A" title="Codeforces Round 728 (Div. 2)">1541A - Pretty Permutations</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The parity (whether $$$n$$$ is odd or even) matters.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Swapping two adjacent cats keeps both of them close to their original location and changes both of their locations.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>If $$$n$$$ is even, the optimal distance is $$$n$$$, and if $$$n$$$ is odd the optimal distance is $$$n+1$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541A">Tutorial is loading...</div></div></div><p><a href="/contest/1541/problem/B" title="Codeforces Round 728 (Div. 2)">1541B - Pleasant Pairs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>$$$i+j \leq 2 \cdot n$$$</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The number of pairs $$$(a, b)$$$ such that $$$a \cdot b \leq x$$$ is $$$O(x log x)$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1541B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/A" title="Codeforces Round 728 (Div. 1)">1540A - Great Graphs</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What's the minimum value that an edge from $$$a$$$ to $$$b$$$ can be?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use edges with negative value whenever you can.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The sum of the values of edges with positive weight must be $$$\geq$$$ the maximum value in the array.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540A">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Tree Array</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Fix the initial node chosen and root the tree there, what is the contribution of each pair of nodes?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Nothing matters besides the path from node $$$a$$$ to node $$$b$$$, and the initially chosen node $$$r$$$.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>You are given two stacks of size $$$a_1$$$ and $$$a_2$$$. In a single step, you randomly choose a stack to remove a single item from. What is the probability that $$$a_1$$$ becomes $$$0$$$ before $$$a_2$$$? Can you extend this argument for an arbitrary probability $$$p$$$ to remove from one of the two stacks, and a probability of $$$1-2p$$$ to do nothing?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540B">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/C2" title="Codeforces Round 728 (Div. 1)">1540C2 - Converging Array (Hard Version)</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What are the invariants? The monovariants?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What is the prefix sum array of the converged array? What is the difference array of the converged array?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you conducted the process on a prefix of size $$$1$$$, then of size $$$2$$$, and on and on?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How many values $$$x$$$ are actually interesting?</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540C2">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Inverse Inversions</a></p><p>Author: <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Master PurpleCrayon">PurpleCrayon</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>The answer is always unique.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Try to figure out what the location of the $$$i$$$-th element would be if you only looked at the first $$$i$$$ elements, then the first $$$i+1$$$, etc. to find an $$$O(nq)$$$ solution.</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Use sqrt decomposition to optimize it.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540D">Tutorial is loading...</div></div></div><p><a href="/contest/1540/problem/E" title="Codeforces Round 728 (Div. 1)">1540E - Tasty Dishes</a></p><p>Author: <a class="rated-user user-orange" href="/profile/ijxjdjd" title="Master ijxjdjd">ijxjdjd</a></p> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How much does each chef's initial dish contribute at time $$$k$$$?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>What if you really, really wanted to use matrix exponentiation?</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>How can you multiply some vectors by a matrix in $$$O(N)$$$ time? (go back to linear algebra class)</p></div></div> <div class="spoiler"><b class="spoiler-title">Hint</b><div class="spoiler-content" style="display: none;"><p>Decompose into linear combinations of eigenvectors.</p></div></div> <div class="spoiler"><b class="spoiler-title">Solution</b><div class="spoiler-content" style="display: none;"><div class="problemTutorial" problemcode="1540E">Tutorial is loading...</div></div></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/1540" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 1)</a> </span> </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/1541" class="notice" style="text-decoration: none;">Codeforces Round 728 (Div. 2)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-191295-92809").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "191295", blogEntryId: "92199", contestId: $(that).attr("data-contestId"), resourceIds: $(that).attr("data-resourceIds") }, function(json) { Codeforces.reloadAndShowMessageOrShowError(json, "Contest detached"); }); }, function () {}, "Yes", "No"); }); }); </script> <div class="roundbox meta borderTopRound borderBottomRound" style=""> <div class="left-meta"> <ul> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-up-92809"><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'>+96</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-92809"><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/PurpleCrayon"><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/PurpleCrayon"> PurpleCrayon </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="Jun/25/2021 20:44">2 years ago</span> </li> <li> <a href="/blog/entry/92199#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/92199#comments"> 170 </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="100805"> <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 (136)</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="808750" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808750" href="?#comment-808750" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808750" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-66" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-66</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808750"> <div class="moveup"> <div class="ttypography"><p>PURPLECRAYON ORZ</p></div> </div> </div> <div class="reply info"> <a class="comment-808750 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808750 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808750"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808751" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hbarp" style="position: relative;"> <img src='https://userpic.codeforces.org/1387715/avatar/c727a810db6ffb66.jpg'/> </a> <div><a href="/profile/hbarp" title="Candidate Master hbarp" class="rated-user user-violet">hbarp</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808751" href="?#comment-808751" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808751" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-83" data-commentUserId="1387715" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-83</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808751"> <div class="moveup"> <div class="ttypography"><p>Damn, so orz round. <a class="rated-user user-orange" href="/profile/PurpleCrayon" title="Мастер PurpleCrayon">PurpleCrayon</a> orz</p></div> </div> </div> <div class="reply info"> <a class="comment-808751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808751"> <li> <div class="comment"> <table class="comment-table" commentId="808805" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/naman1601" style="position: relative;"> <img src='https://userpic.codeforces.org/1703219/avatar/d63fc523dc05fda8.jpg'/> </a> <div><a href="/profile/naman1601" title="Master naman1601" class="rated-user user-orange">naman1601</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808805" href="?#comment-808805" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808805" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-51" data-commentUserId="1703219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-51</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808805"> <div class="moveup"> <div class="ttypography"><p>yeah, amazing problemset, not speedforces at all :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808805 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808805 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808805"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808817" commentParentId="808751"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LOVELY_BOY_" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/LOVELY_BOY_" title="Newbie LOVELY_BOY_" class="rated-user user-gray">LOVELY_BOY_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808817" href="?#comment-808817" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808751" style="font-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="808817" 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="808817" class="CommentVoteFrame" data-commentRating="35" data-commentUserId="2089809" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808817"> <div class="moveup"> <div class="ttypography"><p>LOL <a class="rated-user user-blue" href="/profile/hbarp" title="Эксперт hbarp">hbarp</a>,even you didn't participate in the contest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808817 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808817 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808817"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808753" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DontLookBack" style="position: relative;"> <img src='https://userpic.codeforces.org/1534766/avatar/4eacdc5f9758fc28.jpg'/> </a> <div><a href="/profile/DontLookBack" title="Specialist DontLookBack" class="rated-user user-cyan">DontLookBack</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808753" href="?#comment-808753" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808753" class="CommentVoteFrame" data-commentRating="21" data-commentUserId="1534766" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+21</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808753"> <div class="moveup"> <div class="ttypography"><p>I am curious, how many div2 testers solved D?</p></div> </div> </div> <div class="reply info"> <a class="comment-808753 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808753 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808753"> <li> <div class="comment"> <table class="comment-table" commentId="808826" commentParentId="808753"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/highonjuice" style="position: relative;"> <img src='https://userpic.codeforces.org/1457566/avatar/f7988dd2af03d38b.jpg'/> </a> <div><a href="/profile/highonjuice" title="Pupil highonjuice" class="rated-user user-green">highonjuice</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808826" href="?#comment-808826" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808753" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808826" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1457566" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808826"> <div class="moveup"> <div class="ttypography"><p>like 2 ppl, it was hard for me</p></div> </div> </div> <div class="reply info"> <a class="comment-808826 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808826 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808826"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808757" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Tlatoani" style="position: relative;"> <img src='https://userpic.codeforces.org/614001/avatar/598b4e8358aad1b4.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/Tlatoani" title="Grandmaster Tlatoani" class="rated-user user-red">Tlatoani</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:18">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808757" href="?#comment-808757" style="font-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="808757" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="808757" class="CommentVoteFrame" data-commentRating="121" data-commentUserId="614001" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+121</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808757"> <div class="moveup"> <div class="ttypography"><h4>Alternate solution to <a href="/contest/1540/problem/D" title="Codeforces Round 728 (Div. 1)">1540D - Инвертируем инверсии</a></h4><p>(Read the first nontrivial paragraph of the editorial before reading this alternate solution)</p><p>Let $$$p_r(k) = x$$$ denote that of the numbers $$$p(1), \ldots, p(r)$$$ in sorted order, $$$p(k)$$$ is equal to the $$$x$$$th of these numbers. We will take a decomposition strategy just as the editorial does, though our strategy will be different. We will divide $$$[1, n]$$$ into blocks of length $$$b$$$. For each block covering some interval $$$[l, r]$$$, we will store $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>This means that for any $$$k$$$, if we know $$$p_r(k)$$$ for some block $$$[l, r]$$$, then we can determine $$$p_{r'}(k)$$$ for the block $$$[l', r']$$$ immediately to the right by binary searching on the numbers stored for $$$[l', r']$$$. Therefore, we can perform queries in $$$O\left(\frac n b \lg b\right)$$$.</p><p>We now need to figure out updates. There are probably simple ways to perform updates in $$$O(b\lg b)$$$, but this yields an overall runtime of $$$O(q\sqrt n \lg n)$$$ which is too slow.</p><p>Therefore, we can instead store each block as a segment tree. For each range $$$[l, r]$$$ in the segment tree we store the same thing we store for the whole block: $$$p_r(k)$$$ for each $$$k \in [l, r]$$$ in sorted order.</p><p>We then have to quickly merge two intervals. We can merge two intervals of length $$$\lambda$$$ in $$$O(\lambda \lg \lambda)$$$ by doing binary search just as we did above, but this still only yields $$$O(b\lg b)$$$ update overall. However, these $$$\lambda$$$ binary searches can be optimized using two pointers to $$$O(\lambda)$$$, making the overall update $$$O(b)$$$.</p><p>We thus have $$$O\left(\frac n b \lg b\right)$$$ query and $$$O(b)$$$ update. Therefore, we can choose $$$b = \sqrt{n\lg n}$$$ to attain an overall runtime of $$$O\left(q\sqrt{n\lg n}\right)$$$ just as the editorial does.</p><p><a href="https://codeforces.com/contest/1540/submission/120611645">Submission in Kotlin</a></p><p><a href="https://codeforces.com/contest/1540/submission/120612729">Submission in C++</a></p><p>It is interesting to note that this solution is quite fast. At the time of writing this update, the C++ version is the fastest correct submission (and runs under 1 second!) and the Kotlin version is faster than the vast majority of submissions.</p></div> </div> </div> <div class="reply info"> <a class="comment-808757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808757"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808765" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/hardcode229" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/hardcode229" title="Newbie hardcode229" class="rated-user user-gray">hardcode229</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808765" href="?#comment-808765" style="font-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="808765" 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="808765" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="1635180" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808765"> <div class="moveup"> <div class="ttypography"><p>The 3rd hint for the second problem is same as that of the first problem, is it related or a mistake? <strong>UPD:</strong> it is corrected.</p></div> </div> </div> <div class="reply info"> <a class="comment-808765 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808765 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808765"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808769" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/peanut" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/peanut" title="Specialist peanut" class="rated-user user-cyan">peanut</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:24">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808769" href="?#comment-808769" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808769" class="CommentVoteFrame" data-commentRating="22" data-commentUserId="1167233" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+22</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808769"> <div class="moveup"> <div class="ttypography"><p>speedforces.</p></div> </div> </div> <div class="reply info"> <a class="comment-808769 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808769 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808769"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808781" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/graphs_11" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/graphs_11" title="Specialist graphs_11" class="rated-user user-cyan">graphs_11</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808781" href="?#comment-808781" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808781" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1610110" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808781"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">Problem B Detailed Explanation</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808781 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808781 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808781"> <li> <div class="comment"> <table class="comment-table" commentId="809069" commentParentId="808781"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:40">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809069" href="?#comment-809069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808781" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809069" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809069"> <div class="moveup"> <div class="ttypography"><p>Thank you, very well explained</p></div> </div> </div> <div class="reply info"> <a class="comment-809069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809069"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808790" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PC_E1052" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PC_E1052" title="Pupil PC_E1052" class="rated-user user-green">PC_E1052</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808790" href="?#comment-808790" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808790" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="811219" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808790"> <div class="moveup"> <div class="ttypography"><p>c was too easy, d was too hard. but d was very nice problem though. </p></div> </div> </div> <div class="reply info"> <a class="comment-808790 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808790 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808790"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808793" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808793" href="?#comment-808793" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808793" class="CommentVoteFrame" data-commentRating="58" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+58</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808793"> <div class="moveup"> <div class="ttypography"><p>Paging <a class="rated-user user-legendary" href="/profile/ecnerwala" title="Легендарный гроссмейстер ecnerwala"><span class="legendary-user-first-letter">e</span>cnerwala</a> to explain his solution to D1E if he'd like. It seems offline?</p></div> </div> </div> <div class="reply info"> <a class="comment-808793 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808793 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808793"> <li> <div class="comment"> <table class="comment-table" commentId="808979" commentParentId="808793"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ecnerwala" 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/ecnerwala" title="Legendary Grandmaster ecnerwala" class="rated-user user-legendary"><span class="legendary-user-first-letter">e</span>cnerwala</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808979" href="?#comment-808979" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808793" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808979" class="CommentVoteFrame" data-commentRating="40" data-commentUserId="57502" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+40</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808979"> <div class="moveup"> <div class="ttypography"><p>My solution is $$$O(K N^3 + QN)$$$. I just precomputed the coefficient of each $$$a_i$$$ for each prefix-range for each number of days since person $$$i$$$ becomes positive (only $$$1000$$$ possible days) in $$$O(N \cdot K \cdot N^2)$$$, and then summed up the appropriate ones to answer each query in $$$O(N)$$$. It's written in the offline style to use only $$$O(KN)$$$ memory at a time (grouped by $$$a_i$$$) instead of $$$O(KN^2)$$$.</p><p>My passing submission is just $$$KN^3 / 6$$$ instead of the $$$KN^3$$$ I submitted in contest :'(</p><p>If you guys wanted to prevent this, $$$K$$$ could've been much higher, like $$$1e18$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808979 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808979 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808979"> <li> <div class="comment"> <table class="comment-table" commentId="809002" commentParentId="808979"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809002" href="?#comment-809002" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808979" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809002" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809002"> <div class="moveup"> <div class="ttypography"><p>:( I knew of this solution (it’s why ML is tight) but I didn’t realize that it could be done offline with small memory. Of course $$$K$$$ higher is obvious solution but main issue is that the extra modulos from binary exponentiation make it very hard to pass in Java without allowing other unoptimal solutions through such as precomputing inverses of the matrix. Probably $$$k=10^5$$$ would’ve been a better choice. Thanks.</p></div> </div> </div> <div class="reply info"> <a class="comment-809002 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809002 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809002"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808795" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/zukonit14" style="position: relative;"> <img src='https://userpic.codeforces.org/1192187/avatar/5afd49be87fb87d9.jpg'/> </a> <div><a href="/profile/zukonit14" title="Expert zukonit14" class="rated-user user-blue">zukonit14</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808795" href="?#comment-808795" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808795" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1192187" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808795"> <div class="moveup"> <div class="ttypography"><p>Does Div2 D deserved to be D Problem? According to me it should've been Div2 E.</p></div> </div> </div> <div class="reply info"> <a class="comment-808795 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808795 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808795"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808796" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mangat_angad" style="position: relative;"> <img src='https://userpic.codeforces.org/1449578/avatar/d3cadb0c26e0c11f.jpg'/> </a> <div><a href="/profile/mangat_angad" title="Specialist mangat_angad" class="rated-user user-cyan">mangat_angad</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:35">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808796" href="?#comment-808796" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808796" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1449578" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808796"> <div class="moveup"> <div class="ttypography"><p>I feel like such an idiot for not being able to understand problem C (Div2). For some reason I thought the nodes were connected like this — 1-&gt;2-&gt;3-&gt;....-&gt;N and that we had to minimise answer by adding other edges (of negative weight in case they dont give a negative cycle) to this graph.</p></div> </div> </div> <div class="reply info"> <a class="comment-808796 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808796 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808796"> <li> <div class="comment"> <table class="comment-table" commentId="808896" commentParentId="808796"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808896" href="?#comment-808896" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808796" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808896" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808896"> <div class="moveup"> <div class="ttypography"><p>But that's exactly what I did, and the final answer is the sum of the array — sum of all subarrays. <a href="https://codeforces.com/contest/1541/submission/120611950">120611950</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808896 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808896 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808896"> <li> <div class="comment"> <table class="comment-table" commentId="808941" commentParentId="808896"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808941" href="?#comment-808941" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808896" style="font-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="808941" 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="808941" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808941"> <div class="moveup"> <div class="ttypography"><p>No, that's not what you did. To compute the answer via the method described above, you would have to compute how many elements are lesser than the current element at any given iteration and add them and also keep and their count using a Fenwick tree/ BIT. That's the incorrect approach though because sorting would be more optimal.</p></div> </div> </div> <div class="reply info"> <a class="comment-808941 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808941 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808941"> <li> <div class="comment"> <table class="comment-table" commentId="808952" commentParentId="808941"> <tr> <td class="left"> <div style="position: absolute; left: 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/lbm364dl" style="position: relative;"> <img src='https://userpic.codeforces.org/1839143/avatar/7d03ec22951aa6cf.jpg'/> </a> <div><a href="/profile/lbm364dl" title="Newbie lbm364dl" class="rated-user user-gray">lbm364dl</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808952" href="?#comment-808952" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808941" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808952" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1839143" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808952"> <div class="moveup"> <div class="ttypography"><p>Sorry if I misunderstood things. mangat_angad only mentioned adding negative weighed edges to the 1-&gt;2-&gt;3-&gt;...N graph, which is what I thought to arrive at my solution. The array I mentioned is indeed sorted and formed by distance differences which are the weights in the 1-&gt;2-&gt;3-&gt;...N graph. Unfortunately I'm still too noob to understand the tree structures you mentioned.</p></div> </div> </div> <div class="reply info"> <a class="comment-808952 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808952 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808952"> <li> <div class="comment"> <table class="comment-table" commentId="808955" commentParentId="808952"> <tr> <td class="left"> <div style="position: absolute; left: 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/_reevu_lmao_ktksan_" style="position: relative;"> <img src='https://userpic.codeforces.org/1523904/avatar/85a9d2ddcbbd5d2.jpg'/> </a> <div><a href="/profile/_reevu_lmao_ktksan_" title="Expert _reevu_lmao_ktksan_" class="rated-user user-blue">_reevu_lmao_ktksan_</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808955" href="?#comment-808955" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808952" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808955" class="CommentVoteFrame" class="negative-comment-vote" data-commentRating="-11" data-commentUserId="1523904" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808955"> <div class="moveup"> <div class="ttypography"><p>Nothing unfortunate about it, logic trumps everything </p></div> </div> </div> <div class="reply info"> <a class="comment-808955 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808955 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808955"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808797" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Dannypa" style="position: relative;"> <img src='https://userpic.codeforces.org/1245237/avatar/9fb77289884e4511.jpg'/> </a> <div><a href="/profile/Dannypa" title="Expert Dannypa" class="rated-user user-blue">Dannypa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808797" href="?#comment-808797" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808797" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1245237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808797"> <div class="moveup"> <div class="ttypography"><p>Just want to apologize to authors for the stupidest question, I misread the task..</p></div> </div> </div> <div class="reply info"> <a class="comment-808797 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808797 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808797"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808813" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808813" href="?#comment-808813" style="font-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="808813" 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="808813" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808813"> <div class="moveup"> <div class="ttypography"><p>Can someone tell me the meaning of this line in problem Div2D/Div1B<br /></p> <blockquote><p>Note that, until reaching, l every possible process still has the same probability of reaching b before a. Therefore, we can assume that the process has reached l and calculate the probability from there.</p> </blockquote><p>What same probability are they talking about?</p></div> </div> </div> <div class="reply info"> <a class="comment-808813 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808813 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808813"> <li> <div class="comment"> <table class="comment-table" commentId="808831" commentParentId="808813"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808831" href="?#comment-808831" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808813" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808831" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808831"> <div class="moveup"> <div class="ttypography"><p>Here's what it's trying to say:</p><p>Suppose we start by marking the root. To mark a or b, we must first mark the lca, so we may assume that the lca has just been marked.</p></div> </div> </div> <div class="reply info"> <a class="comment-808831 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808831 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808831"> <li> <div class="comment"> <table class="comment-table" commentId="808840" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808840" href="?#comment-808840" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808840" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808840"> <div class="moveup"> <div class="ttypography"><p>And what does this line mean? <em>&quot;The problem can be rephrased as having two stacks of size dist(l,a) and dist(l,b) with an arbitrary p to remove a node from one of the two stack (and 1−2p to nothing) and finding the probability that dist(l,b) reaches zero before dist(l,a).&quot;</em></p></div> </div> </div> <div class="reply info"> <a class="comment-808840 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808840 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808840"> <li> <div class="comment"> <table class="comment-table" commentId="808857" commentParentId="808840"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:59">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808857" href="?#comment-808857" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808840" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808857" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808857"> <div class="moveup"> <div class="ttypography"><p>Once you've reached the lca $$$l$$$, in a single step you either step closer to $$$a$$$, step closer to $$$b$$$, or step closer to neither.</p></div> </div> </div> <div class="reply info"> <a class="comment-808857 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808857 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808857"> <li> <div class="comment"> <table class="comment-table" commentId="808862" commentParentId="808857"> <tr> <td class="left"> <div style="position: absolute; left: 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/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808862" href="?#comment-808862" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808857" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808862" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808862"> <div class="moveup"> <div class="ttypography"><p>Can you add implementation for this problem please?</p></div> </div> </div> <div class="reply info"> <a class="comment-808862 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808862 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808862"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808849" commentParentId="808831"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808849" href="?#comment-808849" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808831" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808849" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808849"> <div class="moveup"> <div class="ttypography"><p>So, we mark lca first (of course). But why wouldn't it affect the final probability of reaching b before a? I mean, why is it sufficient to calculate the probability after marking lca?</p></div> </div> </div> <div class="reply info"> <a class="comment-808849 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808849 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808849"> <li> <div class="comment"> <table class="comment-table" commentId="808873" commentParentId="808849"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808873" href="?#comment-808873" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808849" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808873" class="CommentVoteFrame" data-commentRating="19" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+19</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808873"> <div class="moveup"> <div class="ttypography"><p>Before marking the lca, there is no way to make more progress towards $$$b$$$ than $$$a$$$ or vice versa. The subset of marked vertices also does not change the probability of moving towards $$$a$$$ or $$$b$$$ after reaching the lca because we're choosing uniformly at random and exactly two vertices are of interest.</p></div> </div> </div> <div class="reply info"> <a class="comment-808873 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808873 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808873"> <li> <div class="comment"> <table class="comment-table" commentId="808883" commentParentId="808873"> <tr> <td class="left"> <div style="position: absolute; left: 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/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808883" href="?#comment-808883" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808873" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808883" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808883"> <div class="moveup"> <div class="ttypography"><p>Now I get it. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808883 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808883 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808883"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808814" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808814" href="?#comment-808814" style="font-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="808814" 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="808814" class="CommentVoteFrame" data-commentRating="30" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+30</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808814"> <div class="moveup"> <div class="ttypography"><p>So, my Solution for <strong>Div1 Problem B</strong> / <strong>Div2 Problem D</strong> / <strong>1540B — Tree Array</strong>:</p><p>Chose two Nodes $$$A$$$ and $$$B$$$ with $$$A&gt;B$$$. </p><p><strong>First DFS:</strong> Find the path from $$$A$$$ to $$$B$$$. I call it $$$path_p$$$. On $$$path_p$$$ mark the distance to $$$B$$$ for each node. </p><p><strong>Second DFS:</strong> For each remaining node $$$N$$$ find the shortest path to $$$path_p$$$. It will hit it at some node of the $$$path_p$$$ which has some distance $$$D$$$ marked on it. We mark $$$N$$$ with $$$D$$$. (See comment below for image.)</p><p><strong>Calculation:</strong> For each node $$$N$$$ we can calculate $$$P_i$$$. $$$P_i$$$ is the probability to reach Node $$$B$$$ before we reach Node $$$A$$$. We sum $$$P_i$$$ for each node. $$$P_i$$$ is also the probability, that the pair of Nodes $$$A$$$ and $$$B$$$ with starting node $$$N$$$ will contribute to the inversion sum. </p><p><strong>Iteration:</strong> We need to repeat this for each pair $$$A$$$ and $$$B$$$. In the end we divide the answer by $$$n$$$, the amount of nodes (the probability to start with Node $$$N$$$). </p><p>This algorithm is $$$O(N^3)$$$. See my Solution <a href="/contest/1540/submission/120603369" title="Посылка 120603369 от OleschY">120603369</a></p> <div class="spoiler"><b class="spoiler-title">How to calculate P_i</b><div class="spoiler-content" style="display: none;"><p>I wrote myself a small helper DP-program to find the regularities. Let $$$D$$$ be the Distance between $$$A$$$ and $$$B$$$ and $$$d$$$ be the distance from the node $$$N$$$ to $$$B$$$. My educated guess was: $$$P_i=\frac{\sum_{i=0}^{d-1}\binom{D-1}{i} }{2^{D-1}}$$$</p> <div class="spoiler"><b class="spoiler-title">Helper Program</b><div class="spoiler-content" style="display: none;"><p>It checks for a path of some length for each Intervall $$$[A,B]$$$ which is already visited, what the probability to reach one node before the other is. </p> <pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; int solve(int n) { vector&lt;vector&lt;double&gt;&gt; dp(n, vector&lt;double&gt;(n, 0)); for(int i = 0; i &lt; n; ++i) { dp[0][i] = 1; dp[i][n - 1] = 0; } dp[0][n - 1] = -1; for(int w = n; w &gt;= 0; w--) { for(int i = 1; i + w &lt; n - 1; i++) { int l = i; int r = w + i; dp[l][r] = 0.5 * (dp[l - 1][r] + dp[l][r + 1]); } } cout &lt;&lt; n &lt;&lt; &quot;\n\n&quot;; for(int i = 0; i &lt; n; i++) { cout &lt;&lt; dp[i][i]*(1&lt;&lt;(n-2)) &lt;&lt; &quot;\n&quot;; } cout &lt;&lt; &quot;\n\n\n\n&quot;; return 0; } //====================== // Technical stuff //====================== int main() { int ntest = 12; for(int test = 2; test &lt; ntest; ++test) { solve(test); } return 0; } </code></pre></div></div></div></div></div> </div> </div> <div class="reply info"> <a class="comment-808814 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808814 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808814"> <li> <div class="comment"> <table class="comment-table" commentId="808843" commentParentId="808814"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808843" href="?#comment-808843" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808814" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808843" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808843"> <div class="moveup"> <div class="ttypography"><p>Can you explain your solution in a little bit more detail? :')</p></div> </div> </div> <div class="reply info"> <a class="comment-808843 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808843 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808843"> <li> <div class="comment"> <table class="comment-table" commentId="808869" commentParentId="808843"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808869" href="?#comment-808869" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808843" style="font-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="808869" 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="808869" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808869"> <div class="moveup"> <div class="ttypography"><p>Oof, I can give you an image, that shows how the distances from the two DFS are distributed on an example. You can see Nodes $$$A$$$ and $$$B$$$ and the numbers are the distances we write into the nodes. </p><p><img alt=" " src="/predownloaded/d8/2f/d82f98ecd2c1b4bd15b3c40e62476f6ae2741a64.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>If you have specific questions about some steps go ahead and ask. </p></div> </div> </div> <div class="reply info"> <a class="comment-808869 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808869 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808869"> <li> <div class="comment"> <table class="comment-table" commentId="810069" commentParentId="808869"> <tr> <td class="left"> <div style="position: absolute; left: 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/Mrajaryan" style="position: relative;"> <img src='https://userpic.codeforces.org/1377953/avatar/e904b3a3a2eac1ad.jpg'/> </a> <div><a href="/profile/Mrajaryan" title="Newbie Mrajaryan" class="rated-user user-gray">Mrajaryan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 15:03">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810069" href="?#comment-810069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808869" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810069" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1377953" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810069"> <div class="moveup"> <div class="ttypography"><p>what does the dp states mean in your helper program? I am unable to understand. Can you please explain?</p></div> </div> </div> <div class="reply info"> <a class="comment-810069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810069"> <li> <div class="comment"> <table class="comment-table" commentId="810097" commentParentId="810069"> <tr> <td class="left"> <div style="position: absolute; left: 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/OleschY" style="position: relative;"> <img src='https://userpic.codeforces.org/1990946/avatar/3401646ac8d5d1d0.jpg'/> </a> <div><a href="/profile/OleschY" title="Master OleschY" class="rated-user user-orange">OleschY</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/29/2021 18:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810097" href="?#comment-810097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-810069" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1990946" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810097"> <div class="moveup"> <div class="ttypography"><p>You have Nodes $$$1$$$ through $$$N$$$, neighbouring IDs are connected. The state $$$dp[l][r]$$$ is the probability, that node $$$N$$$ will be reached before node $$$1$$$ with all the nodes $$$l$$$ through $$$r$$$ marked already. Obviously $$$dp[1][x]=0$$$ and $$$dp[x][N]=1$$$ ($$$dp[1][N]$$$ can't happen). The recurrence is $$$dp[l][r]=(dp[l-1][r]+dp[l][r+1])/2$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-810097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808818" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808818" href="?#comment-808818" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808818" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808818"> <div class="moveup"> <div class="ttypography"><p>I can't grasp the editorial of Div 2 D/ Div 1 B. Can somebody provide a more intuitive explanation?</p></div> </div> </div> <div class="reply info"> <a class="comment-808818 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808818 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808818"> <li> <div class="comment"> <table class="comment-table" commentId="808821" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/parveen1981" style="position: relative;"> <img src='https://userpic.codeforces.org/1556798/avatar/7f833f7b60f261f7.jpg'/> </a> <div><a href="/profile/parveen1981" title="Specialist parveen1981" class="rated-user user-cyan">parveen1981</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:45">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808821" href="?#comment-808821" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808821" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1556798" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808821"> <div class="moveup"> <div class="ttypography"><p>same :(</p></div> </div> </div> <div class="reply info"> <a class="comment-808821 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808821 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808821"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808861" commentParentId="808818"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808861" href="?#comment-808861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808818" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808861" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808861"> <div class="moveup"> <div class="ttypography"><p>Step 1. use linearity of expectation. The answer is</p> <center>$$$\sum_{a&lt;b} P(b\text{ appears before }a). $$$</center><p>Step 2: Observe that if we start by marking a vertex $$$c$$$ on the path between $$$a$$$ and $$$b$$$, and suppose the next marked vertex on the path is $$$d$$$. Then, the probability that $$$d$$$ is between $$$c$$$ and $$$a$$$ and the probability that $$$d$$$ is between $$$c$$$ and $$$b$$$ are both $$$1/2$$$. This is because there are only two choices for $$$d$$$ and we're choosing uniformly at random. This means that the answer only depends on $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p><p>Step 3: run a dp to calculate the probability that we mark $$$b$$$ before $$$a$$$ given $$$\text{dist}(c,a)$$$ and $$$\text{dist}(c,b)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-808861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808861"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808833" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:50">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808833" href="?#comment-808833" style="font-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="808833" 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="808833" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-72" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-72</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808833"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin &gt;&gt; t; while(t--){ int n; cin &gt;&gt; n; long long arr[n]; for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0; for(int i = 0; i &lt; n — 1; i++){ for(int j = arr[i] — 2 — i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } } } cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;; } return 0; }</p><p>/* Accepted code A different approach using arrays (as I don't know what vectors are, haven't read that) I hope this is a optimal approach. Any suggestions related to this are whole-heartedly welcomed. Also, please guide me how could I have optimized the code to a much extent. Thanks in advance! Keep programming! */</p></div> </div> </div> <div class="reply info"> <a class="comment-808833 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808833 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808833"> <li> <div class="comment"> <table class="comment-table" commentId="808844" commentParentId="808833"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808844" href="?#comment-808844" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808833" style="font-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="808844" 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="808844" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-35" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-35</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808844"> <div class="moveup"> <div class="ttypography"><p>.</p></div> </div> </div> <div class="reply info"> <a class="comment-808844 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808844 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808844"> <li> <div class="comment"> <table class="comment-table" commentId="808863" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808863" href="?#comment-808863" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808863" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808863"> <div class="moveup"> <div class="ttypography"><p>Not studied yet, I'm still a beginner, but planning to start soon. Thanks for the guidance.</p></div> </div> </div> <div class="reply info"> <a class="comment-808863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808863"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808879" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/baguettes" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/baguettes" title="International Master baguettes" class="rated-user user-orange">baguettes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808879" href="?#comment-808879" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808879" class="CommentVoteFrame" data-commentRating="20" data-commentUserId="467615" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+20</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808879"> <div class="moveup"> <div class="ttypography"><p>once upon a time, I also did problems while not know what vectors are. sad times :'(</p></div> </div> </div> <div class="reply info"> <a class="comment-808879 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808879 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808879"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808926" commentParentId="808844"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808926" href="?#comment-808926" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808844" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808926" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808926"> <div class="moveup"> <div class="ttypography"><p>There's no issue in not knowing vectors. Yes they are important I agree but not knowing vectors should not be discouraged. I became expert here without knowing anything about vectors plus he is a beginner so he shouldn't be discouraged like this.</p></div> </div> </div> <div class="reply info"> <a class="comment-808926 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808926 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808926"> <li> <div class="comment"> <table class="comment-table" commentId="808927" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Tech.Maniac" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Tech.Maniac" title="Expert Tech.Maniac" class="rated-user user-blue">Tech.Maniac</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808927" href="?#comment-808927" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808927" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="1242860" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808927"> <div class="moveup"> <div class="ttypography"><p>+1, I agree with you. Same I was expert last year solely using arrays</p></div> </div> </div> <div class="reply info"> <a class="comment-808927 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808927 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808927"> <li> <div class="comment"> <table class="comment-table" commentId="809201" commentParentId="808927"> <tr> <td class="left"> <div style="position: absolute; left: 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/Yash.Amin" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Yash.Amin" title="Specialist Yash.Amin" class="rated-user user-cyan">Yash.Amin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809201" href="?#comment-809201" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808927" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809201" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-28" data-commentUserId="1226462" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-28</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809201"> <div class="moveup"> <div class="ttypography"><p>Bas kar bsdk kitna jhooth bolega</p></div> </div> </div> <div class="reply info"> <a class="comment-809201 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809201 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809201"> <li> <div class="comment"> <table class="comment-table" commentId="809215" commentParentId="809201"> <tr> <td class="left"> <div style="position: absolute; left: 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/TechNite" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/TechNite" title="Grandmaster TechNite" class="rated-user user-red">TechNite</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809215" href="?#comment-809215" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809201" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809215" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1340710" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809215"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-blue" href="/profile/Yash.Amin" title="Эксперт Yash.Amin">Yash.Amin</a> Could you please refrain from using foul language on educational discussions. Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-809215 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809215 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809215"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808928" commentParentId="808926"> <tr> <td class="left"> <div style="position: absolute; left: 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/Bungmint" style="position: relative;"> <img src='https://userpic.codeforces.org/1604507/avatar/ffae949e31db6ceb.jpg'/> </a> <div><a href="/profile/Bungmint" title="Master Bungmint" class="rated-user user-orange">Bungmint</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808928" href="?#comment-808928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808926" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808928" class="CommentVoteFrame" data-commentRating="11" data-commentUserId="1604507" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+11</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808928"> <div class="moveup"> <div class="ttypography"><p>Ah my bad, I did not want to come across as being arrogant, but I was genuinely confused that some people did not know vectors although they are using C++.</p></div> </div> </div> <div class="reply info"> <a class="comment-808928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808928"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808839" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dreamkiller04" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dreamkiller04" title="Newbie dreamkiller04" class="rated-user user-gray">dreamkiller04</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808839" href="?#comment-808839" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808839" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2089608" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808839"> <div class="moveup"> <div class="ttypography"><p>Please add implementations too.</p></div> </div> </div> <div class="reply info"> <a class="comment-808839 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808839 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808839"> <li> <div class="comment"> <table class="comment-table" commentId="809106" commentParentId="808839"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809106" href="?#comment-809106" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808839" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809106" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809106"> <div class="moveup"> <div class="ttypography"><p>Simply running two loops and checking every case would give a TLE. So, we might want to minimize the number of operations. For this, we would only consider the cases where the sum of indices is a multiple of an element.</p><p>For this, we would first create two loops, one within the other, first loop iterating i from 0 to (n — 1) with an incrementation of 1. By observation, we can see that the first index for which the sum of indices will be a multiple of arr[i] is (arr[i] — 2 — i).</p><p>So, in the nested loop we will run j = (arr[i] — 2 — i) till (n — 1) with an incrementation of arr[i]. We would ignore the cases where j &lt; 0 or j &gt;= n.</p><p>Finally, we need to check for how many cases this holds (arr[i] * arr[j] = i + j + 2 and j &gt; i).</p><p>Suggestions are welcomed!</p></div> </div> </div> <div class="reply info"> <a class="comment-809106 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809106 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809106"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808842" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808842" href="?#comment-808842" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808842" class="CommentVoteFrame" class="too-negative-comment-vote" data-commentRating="-64" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-64</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808842"> <div class="moveup"> <div class="ttypography"><h1>include&lt;bits/stdc++.h&gt;</h1><p>using namespace std;</p><p>int main(){</p><p>ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);</p><p>int t;</p><p>cin &gt;&gt; t;</p><p>while(t--){</p><p>int n;</p> <pre>cin &gt;&gt; n;</pre><p>long long arr[n];</p> <pre>for(int i = 0; i &lt; n; i++){ cin &gt;&gt; arr[i]; } long long cnt = 0;</pre><p>for(int i = 0; i &lt; n — 1; i++){</p> <pre>for(int j = arr[i] &amp;mdash; 2 &amp;mdash; i; j &lt; n; j += arr[i]){ if(j &lt; 0 || j &gt;= n) continue; else{ if((arr[i] * arr[j] == i + j + 2) &amp;&amp; (j &gt; i)) cnt++; } }</pre><p>}</p><p>cout &lt;&lt; cnt &lt;&lt; &quot;\n&quot;;</p><p>}</p> <pre>return 0;</pre><p>}</p><p>/* Accepted code</p><p>A different approach using arrays (as I don't know what vectors are, haven't read that)</p><p>I hope this is a optimal approach.</p><p>Any suggestions related to this are whole-heartedly welcomed.</p><p>Also, please guide me how could I have optimized the code to a much extent.</p><p>Thanks in advance!</p><p>Keep programming! </p><p>*/</p></div> </div> </div> <div class="reply info"> <a class="comment-808842 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808842 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808842"> <li> <div class="comment"> <table class="comment-table" commentId="808851" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thesinhajee" style="position: relative;"> <img src='https://userpic.codeforces.org/1443047/avatar/76a6dc52e136c889.jpg'/> </a> <div><a href="/profile/thesinhajee" title="Specialist thesinhajee" class="rated-user user-cyan">thesinhajee</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808851" href="?#comment-808851" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808851" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1443047" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808851"> <div class="moveup"> <div class="ttypography"><p>Use spoilers for writing codes, please!</p></div> </div> </div> <div class="reply info"> <a class="comment-808851 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808851 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808851"> <li> <div class="comment"> <table class="comment-table" commentId="808870" commentParentId="808851"> <tr> <td class="left"> <div style="position: absolute; left: 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/noneofyourbusiness" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/noneofyourbusiness" title="Newbie noneofyourbusiness" class="rated-user user-gray">noneofyourbusiness</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808870" href="?#comment-808870" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808851" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808870" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="2000380" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808870"> <div class="moveup"> <div class="ttypography"><p>Actually, this is my first comment. Don't know much of this stuff as of now, but I'll surely take care of it the very next time.</p></div> </div> </div> <div class="reply info"> <a class="comment-808870 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808870 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808870"> <li> <div class="comment"> <table class="comment-table" commentId="809760" commentParentId="808870"> <tr> <td class="left"> <div style="position: absolute; left: 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/sus" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sus" title="Pupil sus" class="rated-user user-green">sus</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 05:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809760" href="?#comment-809760" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808870" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809760" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1749651" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809760"> <div class="moveup"> <div class="ttypography"><p>what problem is your code for</p></div> </div> </div> <div class="reply info"> <a class="comment-809760 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809760 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809760"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="808884" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/sevlll777" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/sevlll777" title="Grandmaster sevlll777" class="rated-user user-red">sevlll777</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808884" href="?#comment-808884" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808884" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="839333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-808884"> <div class="moveup"> <div class="ttypography"><p>NICE CODESTYLE!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-808884 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808884 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808884"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809084" commentParentId="808842"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cj2021" style="position: relative;"> <img src='https://userpic.codeforces.org/1927237/avatar/b64ff59bd9dcf385.jpg'/> </a> <div><a href="/profile/cj2021" title="Newbie cj2021" class="rated-user user-gray">cj2021</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809084" href="?#comment-809084" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808842" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809084" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1927237" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809084"> <div class="moveup"> <div class="ttypography"><p>What is &amp;mdash?</p><p>Just curious to know as haven't seen it before.</p></div> </div> </div> <div class="reply info"> <a class="comment-809084 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809084 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809084"> <li> <div class="comment"> <table class="comment-table" commentId="809097" commentParentId="809084"> <tr> <td class="left"> <div style="position: absolute; left: 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/klahsiv" style="position: relative;"> <img src='https://userpic.codeforces.org/1590145/avatar/1bf86ae3d48e55b.jpg'/> </a> <div><a href="/profile/klahsiv" title="Expert klahsiv" class="rated-user user-blue">klahsiv</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809097" href="?#comment-809097" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809084" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809097" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590145" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809097"> <div class="moveup"> <div class="ttypography"><p>it is minus (-).</p></div> </div> </div> <div class="reply info"> <a class="comment-809097 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809097 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809097"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808848" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/willy108" style="position: relative;"> <img src='https://userpic.codeforces.org/1439320/avatar/d7f79ed4e8b32e9a.jpg'/> </a> <div><a href="/profile/willy108" title="Master willy108" class="rated-user user-orange">willy108</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 21:56">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808848" href="?#comment-808848" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808848" class="CommentVoteFrame" data-commentRating="24" data-commentUserId="1439320" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+24</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808848"> <div class="moveup"> <div class="ttypography"><p>Div2 B can also be done in O(NsqrtN). We know that for a given pair of indeces i+j &lt; 2n, so any pair that a[i] * a[j] &lt; 2n will have to have one of the two terms be &lt;= sqrt(n) (with some off by one errors of course). So the algorithm is to store an array of pairs [array value, index] and sort that array by the value. If the array value is &lt;= sqrt(2n) we can naively loop over the rest of the array in O(n) time and check (be careful about overcount), and if the value is &gt; sqrt(n), we can ignore it. This works since when a[i] * a[j] &lt; 2n one of a[i] or a[j] has to be &lt;= sqrt(2n) and as a result, every pair will be counted.</p></div> </div> </div> <div class="reply info"> <a class="comment-808848 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808848 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808848"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808860" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/bcollet" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/bcollet" title="Master bcollet" class="rated-user user-orange">bcollet</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808860" href="?#comment-808860" style="font-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="808860" 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="808860" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="858059" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808860"> <div class="moveup"> <div class="ttypography"><p>I don't understand in div1 C why it's prefix of b, in the case i=3 we have $$$a_1+a_2+a_3=f_1+f_1+b_1+f_1+b_1+b_2$$$ so $$$f_1=(ap_i-2b_1-b_2)$$$ I believe the general formula is something in the taste of $$$f_1=(ap_i-ibp_{i-1}+bpt_{i-1})/i$$$ where bpt_i=b_1+2b_2+...+ib_i, I think I miss something<br />Edit: corrected</p></div> </div> </div> <div class="reply info"> <a class="comment-808860 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808860 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808860"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808865" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ParsaS" style="position: relative;"> <img src='https://userpic.codeforces.org/1590150/avatar/dc2d8c002d2c5e1e.jpg'/> </a> <div><a href="/profile/ParsaS" title="Candidate Master ParsaS" class="rated-user user-violet">ParsaS</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808865" href="?#comment-808865" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808865" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1590150" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808865"> <div class="moveup"> <div class="ttypography"><p>Nice problems. thanks for almost fast editorial.</p></div> </div> </div> <div class="reply info"> <a class="comment-808865 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808865 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808865"> <li> <div class="comment"> <table class="comment-table" commentId="808871" commentParentId="808865"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/E404_Not_Found" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/E404_Not_Found" title="Expert E404_Not_Found" class="rated-user user-blue">E404_Not_Found</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:07">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808871" href="?#comment-808871" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808865" style="font-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="808871" 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="808871" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1662858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808871"> <div class="moveup"> <div class="ttypography"><p>Yes thanks for fast editorial :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808871 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808871 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808871"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808890" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vikash_8090_b" style="position: relative;"> <img src='https://userpic.codeforces.org/1969032/avatar/a0f23c893ae54e74.jpg'/> </a> <div><a href="/profile/vikash_8090_b" title="Newbie vikash_8090_b" class="rated-user user-gray">vikash_8090_b</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808890" href="?#comment-808890" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808890" class="CommentVoteFrame" data-commentRating="2" data-commentUserId="1969032" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+2</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808890"> <div class="moveup"> <div class="ttypography"><p>is there anyone who can't even solve one question of today's contest ..</p></div> </div> </div> <div class="reply info"> <a class="comment-808890 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808890 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808890"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808892" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 22:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808892" href="?#comment-808892" style="font-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="808892" 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="808892" class="CommentVoteFrame" data-commentRating="-6" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">-6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808892"> <div class="moveup"> <div class="ttypography"><p>Deleted :)</p></div> </div> </div> <div class="reply info"> <a class="comment-808892 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808892 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808892"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808918" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/prituladima" style="position: relative;"> <img src='https://userpic.codeforces.org/116750/avatar/ca46d0256a294b26.jpg'/> </a> <div><a href="/profile/prituladima" title="Pupil prituladima" class="rated-user user-green">prituladima</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808918" href="?#comment-808918" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808918" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="116750" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808918"> <div class="moveup"> <div class="ttypography"><p>Please explain div2c/div1a problem a little bit more. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-808918 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808918 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808918"> <li> <div class="comment"> <table class="comment-table" commentId="808921" commentParentId="808918"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dhruv7888" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/dhruv7888" title="Candidate Master dhruv7888" class="rated-user user-violet">dhruv7888</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/25/2021 23:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808921" href="?#comment-808921" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808918" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808921" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1394279" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808921"> <div class="moveup"> <div class="ttypography"><p>Try out this <a href="https://youtube.com/c/MagentaCobra">channel</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808921 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808921 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808921"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808950" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/jakab922" style="position: relative;"> <img src='https://userpic.codeforces.org/53532/avatar/f9515e974f3ebcb1.jpg'/> </a> <div><a href="/profile/jakab922" title="Specialist jakab922" class="rated-user user-cyan">jakab922</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808950" href="?#comment-808950" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808950" class="CommentVoteFrame" data-commentRating="6" data-commentUserId="53532" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+6</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808950"> <div class="moveup"> <div class="ttypography"><p>I don't really understand the need for a recursive function for the stack emptying probabilities in <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a>. I mean given that you have a stack of size <code>n</code> and and <code>m</code> you can basically have an array of size <code>n + m</code> filled with <code>0</code>s and <code>1</code>s where <code>0</code> at the <code>i</code>th place means that the <code>i</code>th element was taken from the first stack. Any such array which has <code>n</code> <code>0</code>s and <code>m</code> <code>1</code>s correspond to one process and it's easy to see that whoever takes the last spot in the array gets emptied later which gives an easy way to calculate the probabilities. Namely $$$\binom{n + m - 1}{n - 1} / \binom{n + m}{n}$$$ for the first and similar to the other. </p></div> </div> </div> <div class="reply info"> <a class="comment-808950 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808950 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808950"> <li> <div class="comment"> <table class="comment-table" commentId="808959" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/cuom1999" style="position: relative;"> <img src='https://userpic.codeforces.org/253776/avatar/934152bc42a0b10c.jpg'/> </a> <div><a href="/profile/cuom1999" title="Grandmaster cuom1999" class="rated-user user-red">cuom1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808959" href="?#comment-808959" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808959" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="253776" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808959"> <div class="moveup"> <div class="ttypography"><p>If $$$m=2$$$ and $$$n=1$$$, your approach gives $$$\frac{1}{3}$$$. The correct answer should be $$$\frac{1}{4}$$$. </p><p>P/S: I'm also curious if there is any combinatoric approach for this,<a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808959 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808959 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808959"> <li> <div class="comment"> <table class="comment-table" commentId="809004" commentParentId="808959"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:51">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809004" href="?#comment-809004" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808959" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809004" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809004"> <div class="moveup"> <div class="ttypography"><p>I would guess that there’s no easy closed form. You can evaluate in $$$O(n)$$$ however by counting right up paths from $$$(a,0)$$$ to $$$(x,y)$$$ for all $$$a$$$ and multiplying by $$$2^{-steps}$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-809004 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809004 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809004"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809366" commentParentId="808950"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/geekpradd" style="position: relative;"> <img src='https://userpic.codeforces.org/367430/avatar/427394aa7f5a63a0.jpg'/> </a> <div><a href="/profile/geekpradd" title="Candidate Master geekpradd" class="rated-user user-violet">geekpradd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809366" href="?#comment-809366" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808950" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809366" class="CommentVoteFrame" data-commentRating="9" data-commentUserId="367430" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+9</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809366"> <div class="moveup"> <div class="ttypography"><p>The problem with this is that all the possibilities are not equilikely, consider $$$m=2, n=1$$$ and let $$$1$$$ denote entries from the stack of size $$$n$$$. Then the probability of obtaining $$$100$$$ is $$$1/2$$$, while obtaining $$$010$$$ and $$$001$$$ has a probability of $$$1/4$$$. Your approach assumes a uniform prior probability (in which case the answer is indeed $$$1/3$$$ whereas here it is $$$1/4$$$ which is the probability of getting $$$001$$$)</p></div> </div> </div> <div class="reply info"> <a class="comment-809366 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809366 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809366"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/thunderboltz" style="position: relative;"> <img src='https://userpic.codeforces.org/1170396/avatar/4f017b259605bc5c.jpg'/> </a> <div><a href="/profile/thunderboltz" title="Newbie thunderboltz" class="rated-user user-gray">thunderboltz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808951" href="?#comment-808951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170396" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808951"> <div class="moveup"> <div class="ttypography"><p>Problem Div2C/Div1A, Plz somebody explain 3rd hint. I didn't get why this condition must be true </p><p><code>The sum of the values of edges with positive weight must be ≥ the maximum value in the array.</code></p></div> </div> </div> <div class="reply info"> <a class="comment-808951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808951"> <li> <div class="comment"> <table class="comment-table" commentId="808995" commentParentId="808951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/shiftyblock" style="position: relative;"> <img src='https://userpic.codeforces.org/1320630/avatar/69f16f33ccc239b.jpg'/> </a> <div><a href="/profile/shiftyblock" title="Specialist shiftyblock" class="rated-user user-cyan">shiftyblock</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808995" href="?#comment-808995" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808995" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1320630" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808995"> <div class="moveup"> <div class="ttypography"><p>I like to think about C this way: The cheapest node is the root, and the most expensive node, X, is the one with the highest value, D. Therefore no matter how we make our edges, we need at least 1 path from node to X with distance D. So let's build 1 single edge of positive weight from 1 to X with weight D.</p><p>Now from node X, all other nodes are &lt;= D. We can use negative edges to go there. Now the problem just becomes &quot;assign as many negative edges as possible&quot; to the rest of the nodes. </p></div> </div> </div> <div class="reply info"> <a class="comment-808995 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808995 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808995"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="808971" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 00:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808971" href="?#comment-808971" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808971" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808971"> <div class="moveup"> <div class="ttypography"><p>In problem <a href="/contest/1540/problem/B" title="Codeforces Round 728 (Div. 1)">1540B - Древесный массив</a> I agree with everything up to:</p> <blockquote><p>Once l is reached, we now note that the probability that the process &quot;gets closer&quot; to b is always equal to the probability of getting closer to a.</p> </blockquote><p>I agree with this quote if it was about each individual set of marked nodes and single step for them. Because for any individual set of marked nodes, those probabilities is just one over the number of options at the moment. But I don't understand why I should forget about everything else what happens with other parts of tree, because after single step which is neither towards <strong>a</strong> neither towards <strong>b</strong>, the number of options (nodes we can mark on next step) may change.</p></div> </div> </div> <div class="reply info"> <a class="comment-808971 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808971 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808971"> <li> <div class="comment"> <table class="comment-table" commentId="809006" commentParentId="808971"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 02:57">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809006" href="?#comment-809006" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808971" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809006" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809006"> <div class="moveup"> <div class="ttypography"><p>That is correct, but to see how it stays the same you can think of it inductively. Use strong induction and assume probability is the same no matter what the state of the tree is. Then from $$$(x,y)$$$ you always have an equal probability of ending up in one of the two states you can transition to because $$$p$$$ is always the same. Every scenario you enter one state, there’s another scenario with the same probability that enters the other state. So, the probability of entering one of the two states is the same as the other, thus $$$0.5$$$. Hopefully that makes things more clear.</p></div> </div> </div> <div class="reply info"> <a class="comment-809006 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809006 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809006"> <li> <div class="comment"> <table class="comment-table" commentId="809113" commentParentId="809006"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:19">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809113" href="?#comment-809113" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809006" style="font-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="809113" 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="809113" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809113"> <div class="moveup"> <div class="ttypography"><p>Oh thanks, it's clear now. So, base of induction is when only <strong>l</strong> reached, and we can show that probability to make step towards <strong>a</strong> and <strong>b</strong> is same because for each individual set you can go from <strong>l</strong> to <strong>b</strong> instead of going from <strong>l</strong> into <strong>a</strong>, using exactly same steps in between (those steps which doesn't change distances to <strong>a</strong> and <strong>b</strong>). And similar holds for next steps.</p></div> </div> </div> <div class="reply info"> <a class="comment-809113 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809113 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809113"> <li> <div class="comment"> <table class="comment-table" commentId="821713" commentParentId="809113"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 08:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821713" href="?#comment-821713" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809113" style="font-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="821713" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="821713" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-821713"> <div class="moveup"> <div class="ttypography"><p>Can you explain this?</p><p>Assume $$$X$$$ is initially node we chose. Then define a function $$$g$$$ :</p><p>$$$g[a][b][STATE]$$$ = probability to reach a before b while state of the tree we reach is $$$STATE$$$, and $$$a$$$, $$$b$$$ is length of path.</p><p><img alt=" " src="/predownloaded/c2/32/c232d053fe3fbd1dedc06e56db58a7c139157987.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>follow the image, I can see : $$$g[a][b][STATE_x] = \frac{1}{4} (g[a][b][STATE_d] + g[a][b][STATE_e] + g[a — 1][b][closer_a] + g[a][b — 1][closer_b])$$$</p><p>It can easy see that the probability can change. Or I wrong in some where?</p></div> </div> </div> <div class="reply info"> <a class="comment-821713 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821713 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821713"> <li> <div class="comment"> <table class="comment-table" commentId="821861" commentParentId="821713"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/27/2021 18:25">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-821861" href="?#comment-821861" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821713" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="821861" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-821861"> <div class="moveup"> <div class="ttypography"><p>I'll hide my long explanation under spoiler</p> <div class="spoiler"><b class="spoiler-title">horrible wall of text</b><div class="spoiler-content" style="display: none;"><p>To put things into words, I want to define some things. First, suppose we marked some $$$s_1, s_2, s_3 ... s_k$$$ vertices in exact this order. Then, let $$$P(s)$$$ to be probability to mark them in this sequence. It can be decomposed into $$$P(s) = p_1 \cdot p_2 \cdot p_3 \cdot ... \cdot p_k$$$ where $$$p_i = 1/o_{i-1}$$$ where $$$o_i$$$ is number of options at step $$$i$$$ — number of opened vertices, except $$$p_0 = 1/n$$$, or $$$o_0 = n$$$.</p><p>Then, let $$$l = LCA(a, b)$$$ where $$$LCA$$$ is lowest common ancestor. Then, let $$$x_v$$$ to be some sort of 'cost'. For each $$$v$$$ on path between $$$a$$$ and $$$l$$$ it will be distance to $$$l$$$, and $$$-1$$$ everywhere else. Similarly, for each $$$v$$$ on path between $$$b$$$ and $$$l$$$ let $$$y_v$$$ to be distance to $$$l$$$ and $$$-1$$$ everywhere else. Let</p> <center>$$$ A(s) = \max\limits_{v\in s}x_v \\ B(s) = \max\limits_{v\in s}y_v $$$</center><p>Then $$$A(s)$$$ is equal to how far we reach $$$a$$$, and $$$B(s)$$$ is equal to how far we reach $$$b$$$. Let say we are in situation $$$(A(s), B(s))$$$ after marking $$$s$$$, and therefore situation is pair of numbers. Situation $$$(-1,-1)$$$ corresponds that no vertex is marked on path from $$$a$$$ to $$$b$$$. Situation $$$(0,0)$$$ corresponds to only $$$l$$$ marked on path from $$$a$$$ to $$$b$$$. And situation $$$(1,0)$$$ corresponds to $$$l$$$ and single vertex towards $$$a$$$ is marked.</p><p>Finally, let say sequence of marks $$$s$$$ reached state $$$(A(s), B(s))$$$ if either $$$A(s) = x_{s_k}$$$ or $$$B(s) = y_{s_k}$$$, in other words, last vertex is on path from $$$a$$$ to $$$b$$$ and it did change situation.</p><p>Now, what we want to prove is following:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha+1,\beta)} P(s) = \sum\limits_{s\;reached\;(\alpha,\beta+1)} P(s)$$$</center><p><strong>For some fixed</strong> $$$s_1$$$, which is root we chosen. And the way we prove it is that $$$s$$$ that is reached $$$(\alpha+1,\beta)$$$ consists of $$$u$$$ that reached $$$(\alpha,\beta)$$$ plus additional steps: $$$w$$$ plus $$$s_k$$$. So $$$s = u..w..s_k$$$ where $$$..$$$ is concatenation. It's easy to see what none of vertices from $$$w$$$ is on path from $$$a$$$ to $$$b$$$. Also, it's easy to see that we could instead of choosing $$$s_k$$$ could choose vertex $$$z$$$ towards $$$b$$$, and it would have same probability. In other words $$$P(s) = P(u..w..z)$$$. And this $$$u..w..z$$$ should reach state $$$(\alpha, \beta+1)$$$. So it should be in right side sum of our equation we want to prove.</p><p>So, for any $$$s$$$ from left sum, we can make $$$s'$$$ from right sum in unique way, and it will have same $$$P(s) = P(s')$$$. Similarly, for any $$$s$$$ from right sum, we can make $$$s'$$$ from left sum in unique way, and it will have same $$$P(s) = P(s')$$$. So this is bijection, and each element from left sum corresponds to element from right sum with same value, so those sums should have same value. Therefore it's equality.</p><p>Initially I wanted to trim $$$s$$$ from $$$(\alpha+1,\beta)$$$ to $$$(\alpha,\beta)$$$ and show similar thing based on following sum:</p> <center>$$$\sum\limits_{s\;reached\;(\alpha,\beta)} P(s)$$$</center><p>Which is probability to reach state $$$(\alpha, \beta)$$$, but luckily it didn't required. I'll use notation $$$P(reach(\alpha, \beta))$$$ for this probability.</p><p>Thing that is not covered though: why this equality can be translated into probability $$$= 1/2$$$? Well, from $$$(\alpha, \beta)$$$ you eventually will reach either $$$(\alpha+1,\beta)$$$ or $$$(\alpha,\beta+1)$$$, so you can see this as example of Law of total probability. $$$P(reach(\alpha, \beta)) = P(reach (\alpha+1, \beta)) + P(reach (\alpha, \beta+1))$$$, because events $$$(\alpha+1,\beta)$$$ and $$$(\alpha,\beta+1)$$$ are disjoint events given $$$(\alpha, \beta)$$$ is reached. And we proved they have equal probability so $$$P(reach(\alpha, \beta)) = 2\cdot P(reach (\alpha+1, \beta))$$$, so $$$P(reach (\alpha+1, \beta)) = 1/2\cdot P(reach(\alpha, \beta))$$$ which we actually use.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-821861 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-821861 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-821861"> <li> <div class="comment"> <table class="comment-table" commentId="822027" commentParentId="821861"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/28/2021 13:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822027" href="?#comment-822027" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-821861" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="822027" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822027"> <div class="moveup"> <div class="ttypography"><p>Oh, sorry, there is one missing part. We proved $$$P(reached(\alpha+1,\beta))=P(reached(\alpha,\beta+1))$$$ <strong>given</strong> $$$(\alpha,\beta)$$$ is reached, but this is actually what we need. This <strong>given</strong> condition is what I missed. Without <strong>given</strong> we could reach $$$(\alpha+1,\beta)$$$ from reaching $$$(\alpha+1,\beta-1)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-822027 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822027 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822027"> <li> <div class="comment"> <table class="comment-table" commentId="822370" commentParentId="822027"> <tr> <td class="left"> <div style="position: absolute; left: 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/ngk_manh" style="position: relative;"> <img src='https://userpic.codeforces.org/1451475/avatar/70f0e7688befffc9.jpg'/> </a> <div><a href="/profile/ngk_manh" title="Specialist ngk_manh" class="rated-user user-cyan">ngk_manh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 13:30">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822370" href="?#comment-822370" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822027" style="font-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="822370" revisionCount="5" revision="5"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">5</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="822370" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1451475" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822370"> <div class="moveup"> <div class="ttypography"><p>Thanks for amz explain. I realize that I had some missunderstand in the way we calc $$$P(reach\ A\ before\ B)$$$</p><p>This's exactly what in my mind one day ago: let $$$s = ...a...b...$$$ where $$$a$$$ and $$$b$$$ is node $$$a$$$ and node $$$b$$$, &quot;$$$...$$$&quot; mean some node between them which we chose them in exactly that order, or in other word, $$$s$$$ is state represent what we chose (exact in this order) I think $$$P(reach\ A\ before\ B)$$$ (or $$$P(A&lt;B)$$$) must be calculate in this way :</p><p>$$$P(A&lt;B) = \sum_{\substack{all\ s\ which\ a&lt;b}} P(s)$$$</p><p>But unfortunately, it's wrong (may be, or I still missunderstanding)</p><p>$$$P(A) = \sum_{\substack{all\ B[i]\ \subseteq\ A}} P(B[i])$$$ if and only if all $$$B[i]$$$ are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-822370 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822370 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822370"> <li> <div class="comment"> <table class="comment-table" commentId="822755" commentParentId="822370"> <tr> <td class="left"> <div style="position: absolute; left: 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/r57shell" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/r57shell" title="Expert r57shell" class="rated-user user-blue">r57shell</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/29/2021 22:11">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-822755" href="?#comment-822755" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-822370" style="font-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="822755" 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="822755" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="254555" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-822755"> <div class="moveup"> <div class="ttypography"><p>$$$P(A &lt; B)$$$ in your terms is exactly what we need (if a = A and b = B).</p><p>I don't understand last formula, everything else looks fine.</p><p>And to find $$$P(A &lt; B)$$$ we use fact above and calculate all possible ways to reach $$$a$$$ earlier than $$$b$$$ we use $$$(\alpha, \beta)$$$ states using my notation: you either get $$$\alpha$$$ equal to dist to $$$a$$$ when $$$\beta$$$ = 0, or $$$\beta$$$ = 1, or 2, or 3...</p> <center>$$$ P(A &lt; B) = \\ =\sum\limits_{i=0}^{dist(b,l)}P(reach(dist(a,l),i)\;given\; reached(dist(a,l)-1,i)) \\ = \sum\limits_{i=0}^{dist(b,l)}P(reached(dist(a,l)-1,i))\cdot \frac{1}{2} $$$</center><p>Or you can rephrase task into other task with two kind of balls. What probability to remove all balls of one kind earlier than other, if you pick one or other kind of ball with probability 1/2.</p></div> </div> </div> <div class="reply info"> <a class="comment-822755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-822755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-822755"> </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="808983" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/xsc" style="position: relative;"> <img src='https://userpic.codeforces.org/343/avatar/9eaf243b1eb8c3d4.jpg'/> </a> <div><a href="/profile/xsc" title="Specialist xsc" class="rated-user user-cyan">xsc</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 01:48">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-808983" href="?#comment-808983" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="808983" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="343" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-808983"> <div class="moveup"> <div class="ttypography"><p>Div2 D, O(N^4) solution <a href="/contest/1541/submission/120623566" title="Посылка 120623566 от xsc">120623566</a></p></div> </div> </div> <div class="reply info"> <a class="comment-808983 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-808983 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-808983"> <li> <div class="comment"> <table class="comment-table" commentId="809278" commentParentId="808983"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/DavidXu_JJ" style="position: relative;"> <img src='https://userpic.codeforces.org/2003708/avatar/623dc8036b4e9d72.jpg'/> </a> <div><a href="/profile/DavidXu_JJ" title="Expert DavidXu_JJ" class="rated-user user-blue">DavidXu_JJ</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809278" href="?#comment-809278" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-808983" style="font-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="809278" 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="809278" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2003708" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809278"> <div class="moveup"> <div class="ttypography"><p>Your code really helps me a lot in debugging,thanks.</p><p>By the way,it's weired that I get Wrong6 when I try to optimize to O(N^3*logN) by binary search on tree.</p><p>I have tested my function on other online judge and my function seems to be correct.</p></div> </div> </div> <div class="reply info"> <a class="comment-809278 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809278 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809278"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809018" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ducati" style="position: relative;"> <img src='https://userpic.codeforces.org/699102/avatar/eff3c352646e914e.jpg'/> </a> <div><a href="/profile/ducati" title="Grandmaster ducati" class="rated-user user-red">ducati</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 03:39">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809018" href="?#comment-809018" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809018" class="CommentVoteFrame" data-commentRating="5" data-commentUserId="699102" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+5</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809018"> <div class="moveup"> <div class="ttypography"><p>Although Div.2 D is harder than ever, in my opinion, it's such a useful and excellent problem.</p></div> </div> </div> <div class="reply info"> <a class="comment-809018 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809018 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809018"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809046" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KanishkGoel" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/KanishkGoel" title="Expert KanishkGoel" class="rated-user user-blue">KanishkGoel</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809046" href="?#comment-809046" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809046" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1917239" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809046"> <div class="moveup"> <div class="ttypography"><p>Is it usual for people to post solutions online during the contest like this channel? <a href="https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ">https://youtube.com/channel/UCIAiAwwbj9OLmbZehfc28OQ</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809046 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809046 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809046"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809051" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 05:46">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809051" href="?#comment-809051" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809051"> <div class="moveup"> <div class="ttypography"><p>Can anyone please explain why this submission <a href="/contest/1541/submission/120562335" title="Посылка 120562335 от Karnania7201">120562335</a> is failing for Div2 B? It would be a great help.</p></div> </div> </div> <div class="reply info"> <a class="comment-809051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809051"> <li> <div class="comment"> <table class="comment-table" commentId="809076" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809076" href="?#comment-809076" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809076" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809076"> <div class="moveup"> <div class="ttypography"><p>Bro you did not included the condition that i and j should be different i.e (i != j) because it is given in question that no are distinct</p></div> </div> </div> <div class="reply info"> <a class="comment-809076 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809076 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809076"> <li> <div class="comment"> <table class="comment-table" commentId="809079" commentParentId="809076"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:08">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809079" href="?#comment-809079" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809076" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809079" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809079"> <div class="moveup"> <div class="ttypography"><p>I think its covered as I started j from i+1. I tried that explicitly too but it didn't work. I wrote the same idea in a different way and it worked but this kind of implementation is not working.</p></div> </div> </div> <div class="reply info"> <a class="comment-809079 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809079 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809079"> <li> <div class="comment"> <table class="comment-table" commentId="809082" commentParentId="809079"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:20">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809082" href="?#comment-809082" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809079" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809082" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809082"> <div class="moveup"> <div class="ttypography"><p>yeah, you are right, I run your code using vector instead of creating memeset it worked fine, i guess there is some problem in that. <a href="https://codeforces.com/contest/1541/submission/120633207">120633207</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809082 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809082 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809082"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809081" commentParentId="809051"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/_NICkk" style="position: relative;"> <img src='https://userpic.codeforces.org/1543175/avatar/6084dd87f2c1cad9.jpg'/> </a> <div><a href="/profile/_NICkk" title="Expert _NICkk" class="rated-user user-blue">_NICkk</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:17">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809081" href="?#comment-809081" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809051" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809081" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1543175" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809081"> <div class="moveup"> <div class="ttypography"><p>Only fault in your code is that you didn't used memset correctly </p><p>I just changed your memset with this &quot; memset(ind, 0, sizeof(ind)) &quot; and it worked perfectly fine</p></div> </div> </div> <div class="reply info"> <a class="comment-809081 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809081 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809081"> <li> <div class="comment"> <table class="comment-table" commentId="809091" commentParentId="809081"> <tr> <td class="left"> <div style="position: absolute; left: 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/Karnania7201" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Karnania7201" title="Expert Karnania7201" class="rated-user user-blue">Karnania7201</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:37">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809091" href="?#comment-809091" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809081" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809091" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1540602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809091"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot to both of you. I shouldn't have used it without properly knowing about it. </p></div> </div> </div> <div class="reply info"> <a class="comment-809091 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809091 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809091"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809064" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/vrintle" style="position: relative;"> <img src='https://userpic.codeforces.org/1991777/avatar/24d9007095afbbb6.jpg'/> </a> <div><a href="/profile/vrintle" title="Master vrintle" class="rated-user user-orange">vrintle</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809064" href="?#comment-809064" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809064" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1991777" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809064"> <div class="moveup"> <div class="ttypography"><p>Instead of $$$a_i \cdot a_j \leq 2n$$$, we could also check $$$a_i \cdot a_j \leq i+n$$$ which is a bit faster ($$$ \sim 62ms$$$).</p></div> </div> </div> <div class="reply info"> <a class="comment-809064 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809064 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809064"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809066" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809066" href="?#comment-809066" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809066" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809066"> <div class="moveup"> <div class="ttypography"><p>can anyone explain B. pleasant pairs more easy words?? </p></div> </div> </div> <div class="reply info"> <a class="comment-809066 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809066 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809066"> <li> <div class="comment"> <table class="comment-table" commentId="809067" commentParentId="809066"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Pulkitgo" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Pulkitgo" title="Newbie Pulkitgo" class="rated-user user-gray">Pulkitgo</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809067" href="?#comment-809067" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809066" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809067" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="1617644" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809067"> <div class="moveup"> <div class="ttypography"><p>And also what is ask in 3rd question i cant understand what asked in it</p></div> </div> </div> <div class="reply info"> <a class="comment-809067 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809067 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809067"> <li> <div class="comment"> <table class="comment-table" commentId="809070" commentParentId="809067"> <tr> <td class="left"> <div style="position: absolute; left: 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/MoHitman" style="position: relative;"> <img src='https://userpic.codeforces.org/1592812/avatar/a2d7551d2d7d72dd.jpg'/> </a> <div><a href="/profile/MoHitman" title="Expert MoHitman" class="rated-user user-blue">MoHitman</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 06:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809070" href="?#comment-809070" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809067" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809070" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1592812" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809070"> <div class="moveup"> <div class="ttypography"><p><a href="https://www.youtube.com/watch?v=xCj_ZR5kENo">https://www.youtube.com/watch?v=xCj_ZR5kENo</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809070 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809070 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809070"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809098" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 07:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809098" href="?#comment-809098" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809098" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809098"> <div class="moveup"> <div class="ttypography"><p>For those who are searching for a simple solution for great Graphs problems in O (nlogn). <a href="https://codeforces.com/contest/1541/submission/120600816">https://codeforces.com/contest/1541/submission/120600816</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809098 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809098 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809098"> <li> <div class="comment"> <table class="comment-table" commentId="809119" commentParentId="809098"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/fjvzr" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/fjvzr" title="Newbie fjvzr" class="rated-user user-gray">fjvzr</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809119" href="?#comment-809119" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809098" style="font-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="809119" 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="809119" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1623986" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809119"> <div class="moveup"> <div class="ttypography"><p>Bro can u explain this soln????? i thought of taking all pairs that give negative edges except for the adjacent pairs.... bt getting wrong ans in 3rd 4th test case.....</p><p>while(n&gt;2) { sum-=(n-2)*(llabs(a[j]-a[i])); n--; // n = size i++; // i = 0 j--; // j = n-1 } cout&lt;&lt;sum&lt;&lt;endl;</p><p><a href="https://codeforces.com/contest/1541/submission/120636509">mysoln</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809119 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809119 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809119"> <li> <div class="comment"> <table class="comment-table" commentId="809124" commentParentId="809119"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:38">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809124" href="?#comment-809124" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809119" style="font-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="809124" 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="809124" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809124"> <div class="moveup"> <div class="ttypography"><p>My solution is simple. First sort the array. </p><p>Then start connecting adjacent values with their differences. This way sum of all edges with positive weight will be same as the sum of adjacent differences in the array.</p><p>After that start making negative edges for every i. So each i will have i negative edges. Where negative weight is same as -(arr[i] — arr[j]).</p><p>Instead of search it for every j I have formula as (prefixsum till i) — arr[i]*i</p></div> </div> </div> <div class="reply info"> <a class="comment-809124 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809124 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809124"> <li> <div class="comment"> <table class="comment-table" commentId="809132" commentParentId="809124"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:49">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809132" href="?#comment-809132" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809124" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809132" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809132"> <div class="moveup"> <div class="ttypography"><p>can you tell me why are we sorting the array for a particular node call it x we need to add a negative weight from x to 1 , x to 2 x to 3 till x to x-1 keeping in mind the the path sum doesn't become negative so why are we sorting the array</p></div> </div> </div> <div class="reply info"> <a class="comment-809132 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809132 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809132"> <li> <div class="comment"> <table class="comment-table" commentId="809135" commentParentId="809132"> <tr> <td class="left"> <div style="position: absolute; left: 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/praveen_naik__" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/praveen_naik__" title="Pupil praveen_naik__" class="rated-user user-green">praveen_naik__</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809135" href="?#comment-809135" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809132" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809135" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1323667" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809135"> <div class="moveup"> <div class="ttypography"><p>We are sorting values only once so as to connect neighboring nodes with minimum values,i.e. difference b/w consecutive values.<br /> From this sum of positive edges will be minimum.</p></div> </div> </div> <div class="reply info"> <a class="comment-809135 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809135 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809135"> <li> <div class="comment"> <table class="comment-table" commentId="809139" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809139" href="?#comment-809139" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809139" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809139"> <div class="moveup"> <div class="ttypography"><p>ohhh thanks I got it</p></div> </div> </div> <div class="reply info"> <a class="comment-809139 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809139 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809139"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809145" commentParentId="809135"> <tr> <td class="left"> <div style="position: absolute; left: 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/abu123" style="position: relative;"> <img src='https://userpic.codeforces.org/2091026/avatar/cddc8b511c8cc3d6.jpg'/> </a> <div><a href="/profile/abu123" title="Specialist abu123" class="rated-user user-cyan">abu123</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:14">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809145" href="?#comment-809145" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809135" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809145" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="2091026" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809145"> <div class="moveup"> <div class="ttypography"><p>My solution is working now I only needed to sort the array my code would have been accepted during the contest :(</p></div> </div> </div> <div class="reply info"> <a class="comment-809145 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809145 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809145"> </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="809116" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Ken_KaNeKi_997" style="position: relative;"> <img src='https://userpic.codeforces.org/1737228/avatar/50ceb845253df5d4.jpg'/> </a> <div><a href="/profile/Ken_KaNeKi_997" title="Newbie Ken_KaNeKi_997" class="rated-user user-gray">Ken_KaNeKi_997</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:22">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809116" href="?#comment-809116" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809116" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1737228" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809116"> <div class="moveup"> <div class="ttypography"><p>can anyone explain div2 B plz</p></div> </div> </div> <div class="reply info"> <a class="comment-809116 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809116 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809116"> <li> <div class="comment"> <table class="comment-table" commentId="809204" commentParentId="809116"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:55">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809204" href="?#comment-809204" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809116" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809204" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809204"> <div class="moveup"> <div class="ttypography"><p><a href="https://codeforces.com/blog/entry/92199#comment-809178">here</a></p></div> </div> </div> <div class="reply info"> <a class="comment-809204 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809204 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809204"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809122" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 08:34">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809122" href="?#comment-809122" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809122" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809122"> <div class="moveup"> <div class="ttypography"><p>Beautiful Problems. Amazing Round!!!!</p></div> </div> </div> <div class="reply info"> <a class="comment-809122 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809122 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809122"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809156" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dummybawa" style="position: relative;"> <img src='https://userpic.codeforces.org/1704408/avatar/1522f670cd21321.jpg'/> </a> <div><a href="/profile/dummybawa" title="Expert dummybawa" class="rated-user user-blue">dummybawa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 09:28">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809156" href="?#comment-809156" style="font-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="809156" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809156" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1704408" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809156"> <div class="moveup"> <div class="ttypography"><p>UPD: It's wrong. </p></div> </div> </div> <div class="reply info"> <a class="comment-809156 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809156 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809156"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809178" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:00">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809178" href="?#comment-809178" style="font-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="809178" 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="809178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809178"> <div class="moveup"> <div class="ttypography"><p>For DIV 2C/1A can anyone explain with this test case N = 6 and D = 0 1 2 3 2 3. What are the edges that we can have with their weights?</p></div> </div> </div> <div class="reply info"> <a class="comment-809178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809178"> <li> <div class="comment"> <table class="comment-table" commentId="809198" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Zemrith" style="position: relative;"> <img src='https://userpic.codeforces.org/1159882/avatar/2a6566e372882267.jpg'/> </a> <div><a href="/profile/Zemrith" title="Expert Zemrith" class="rated-user user-blue">Zemrith</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:43">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809198" href="?#comment-809198" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-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="809198" 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="809198" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1159882" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809198"> <div class="moveup"> <div class="ttypography"><p>Hello! The answer would be -18.</p><p>Diagram: <img alt=" " src="/predownloaded/8c/88/8c88a0230dea9f499896ee59def659611c605976.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Notice that once you sort the distances, the adjacent nodes have no effect on your final answer. But you can add negative edges as long as they are not adjacent, resulting in such a diagram. Hence you can use prefix sums to solve the problem. (if x nodes came before this, for each node, the answer to add is (x-1)*curr value — csum of first (x-1) nodes). </p><p>Hope that made sense!</p></div> </div> </div> <div class="reply info"> <a class="comment-809198 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809198 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809198"> <li> <div class="comment"> <table class="comment-table" commentId="809218" commentParentId="809198"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:27">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809218" href="?#comment-809218" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809198" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809218" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809218"> <div class="moveup"> <div class="ttypography"><p>Thank you <a class="rated-user user-cyan" href="/profile/Zemrith" title="Специалист Zemrith">Zemrith</a> for so much detail explanation and the solution too it helped me a lot.</p></div> </div> </div> <div class="reply info"> <a class="comment-809218 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809218 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809218"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809199" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Forrest_Gump" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Forrest_Gump" title="Expert Forrest_Gump" class="rated-user user-blue">Forrest_Gump</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809199" href="?#comment-809199" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809199" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1517763" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809199"> <div class="moveup"> <div class="ttypography"><p>first sort the array they will from non negative weight edges. 0 -&gt; 1 -&gt; 2 -&gt; 2 -&gt; 3 -&gt; 3 so the non negative weights will be 1 | 1 | 0 | 1 | 0. form here greedily build most negative weights(backward edges) such that there are no negative cycles.</p></div> </div> </div> <div class="reply info"> <a class="comment-809199 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809199 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809199"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809203" commentParentId="809178"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ilidar" style="position: relative;"> <img src='https://userpic.codeforces.org/18729/avatar/9451111847bb77f5.jpg'/> </a> <div><a href="/profile/ilidar" title="Pupil ilidar" class="rated-user user-green">ilidar</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 10:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809203" href="?#comment-809203" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809178" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809203" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="18729" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809203"> <div class="moveup"> <div class="ttypography"><p>First you can sort D and get: <code> N = 6, D = [0, 1, 2, 2, 3, 3] </code></p><p>Now calculate the diffs:</p><p><code>diffs = [1, 1, 0, 1, 0]</code></p><p>The edges for this graph could be something like this:</p> <pre><code> 1 1 0 1 0 &lt;- forward edges 1 &lt;-&gt; 2 &lt;-&gt; 3 &lt;-&gt; 4 &lt;-&gt; 5 &lt;-&gt; 6 -1 -1 0 -1 0 &lt;- backward edges </code></pre><p>Now you have to add more negatives edges, and you could do this by choosing some <code>i</code> and <code>j</code>, <code>i &lt; j</code> and add an edges from <code>j</code> to <code>i</code>, and the weight will be sum of the values from <code>diff[i]</code> to <code>diff[j]</code>.</p><p>Another way to think about this is: look at <code>D</code> array, it represents distances between adjacent nodes, all we have to do is add all of the edges with length 2, then all of the edges of length 3, ..., all of the edges of length <code>N - 1</code>.</p><p>So, for our case we would have these edges</p> <pre><code>a b W ------- 1 2 - 1 2 3 - 1 3 4 - 0 &lt;- adjacent forward edges 4 5 - 1 5 6 - 0 2 1 - -1 3 2 - -1 4 3 - 0 &lt;- adjacent backward edges 5 4 - -1 6 5 - 0 3 1 - -2 4 2 - -1 5 3 - -1 &lt;- edges of length 2 6 4 - -1 4 1 - -2 5 2 - -2 &lt;- edges of length 3 6 3 - -1 5 1 - -3 6 2 - -2 &lt;- edges of length 4 6 1 - -3 &lt;- edges of length 5 </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809203 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809203 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809203"> <li> <div class="comment"> <table class="comment-table" commentId="809221" commentParentId="809203"> <tr> <td class="left"> <div style="position: absolute; left: 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/goingOn" style="position: relative;"> <img src='https://userpic.codeforces.org/1528417/avatar/7edc6aa502f53b2f.jpg'/> </a> <div><a href="/profile/goingOn" title="Specialist goingOn" class="rated-user user-cyan">goingOn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 11:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809221" href="?#comment-809221" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809203" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809221" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1528417" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809221"> <div class="moveup"> <div class="ttypography"><p>Thank You <a class="rated-user user-green" href="/profile/ilidar" title="Ученик ilidar">ilidar</a> for clearing my doubt and for detailed explaination.</p></div> </div> </div> <div class="reply info"> <a class="comment-809221 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809221 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809221"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809280" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:15">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809280" href="?#comment-809280" style="font-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="809280" revisionCount="7" revision="7"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">7</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809280" class="CommentVoteFrame" data-commentRating="18" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+18</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809280"> <div class="moveup"> <div class="ttypography"><p>Could someone please provide a more strict intuition or insight of Div2D/Div1B of why &quot;the actual probability p does not matter&quot;? The intuition in the editorial is still alien to me of why those choices of not progess toward to either stacks (and probability 'p' also changes from time to time too) doesn't matter.</p><p>Update: Here is the intuition I came up with (The strict proof can be found in the comment of the author below)</p><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left) in some states of the current tree.</p><p>now, we will try break this $$$dp_{i,j}$$$ down into the sum of $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$</p><p>We will try to illustrate this with trying to split and color, either red or blue, a stick of length $$$1$$$. The length of the sticks representing the 'probability', and the color of the sticks will represent $$$dp_{i-1,j}$$$(red) or $$$dp_{i,j-1}$$$(blue), depending on the color.</p><p>Suppose in the current state, we have probability $$$p$$$ for choosing to pop each stacks, and the rest $$$1-2p$$$ of doing nothing. The picture will look like this:</p><p><a href="https://ibb.co/q9HjQTm"><img alt="Tree-Array-Rep" border="0" src="/predownloaded/13/57/135732d2b0967af0f76c1dba28df72086f234c7d.png" style="max-width: 100.0%;max-height: 100.0%;" /></a></p><p>We will split the stick equally(*) into several sticks of length $$$p$$$, and then color two of them red and blue. (* We can split it evenly because in the original problem, $$$p$$$ is in the form $$$\frac{1}{number\ of\ candidate\ unmark\ nodes}$$$ ) Now, the remaining sticks represent the state of $$$dp_{i,j}$$$ again (in some other state of the entire tree, so might be in some different $$$p$$$). That means we will split those sticks similary.</p><p>The key observations is:</p><p>1) We know that, in the original problem, if we keep picking nodes that aren't progressing toward the target nodes, we will run out of nodes eventually and finally choose the two nodes. That means, all the sticks will eventually colored into 'red' and 'blue'.</p><p>2) When we split a stick into several smaller equal length sticks, we will color two of them into red and blue. <strong>Those two sticks always have the same length</strong>. That means, the total length of blue sticks and the total length of red sticks will be equal in the end.</p><p>Analogically, that means, eventually, $$$dp_{i,j}$$$ will split into $$$dp_{i-1,j}$$$ and $$$dp_{i,j-1}$$$ evenly, no matter $$$p$$$ might be or the state of tree of $$$dp_{i,j}$$$ might be. Therefore, $$$dp_{i,j} = \frac{1}{2} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$</p></div> </div> </div> <div class="reply info"> <a class="comment-809280 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809280 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809280"> <li> <div class="comment"> <table class="comment-table" commentId="809284" commentParentId="809280"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 14:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809284" href="?#comment-809284" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809280" style="font-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="809284" 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="809284" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809284"> <div class="moveup"> <div class="ttypography"><p>Let $$$dp_{i,j}$$$ = the probability of emptying the first stack (which now have $$$i$$$ things left) before the second stack (which now have $$$j$$$ things left), with having arbitary probability $$$0 &lt; p \leq 0.5$$$ of chosing to pick the top of each stack (and $$$1-2p$$$ for doing nothing). Then</p><p>$$$dp_{i,j}=\int_{0}^{0.5} x \cdot (dp_{i-1,j}+dp_{i,j-1}) + (1-2x) \cdot dp_{i,j} \,dx$$$</p><p>Solving the equation, we get $$$dp_{i,j}=\frac{1}{6} \cdot (dp_{i-1,j}+dp_{i,j-1})$$$ What is the mistake in this logic?</p></div> </div> </div> <div class="reply info"> <a class="comment-809284 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809284 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809284"> <li> <div class="comment"> <table class="comment-table" commentId="809399" commentParentId="809284"> <tr> <td class="left"> <div style="position: absolute; left: 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/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:53">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809399" href="?#comment-809399" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809284" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809399" class="CommentVoteFrame" data-commentRating="13" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+13</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809399"> <div class="moveup"> <div class="ttypography"><p>The biggest issue with this logic is that it's assuming $$$p$$$ is arbitrary chosen from a certain state. While $$$p$$$ can be anything in the world, it is always an exact number from a certain state, hence why an integral is wrong. </p><p>As a different type of intuition, you can think, &quot;is it more likely to reach $$$(i-1, j)$$$ than state $$$(i, j-1)$$$&quot;? and vice versa. For me at least, I don't see how it's possible for either of those questions to be true, so they should be equal.</p><p>If you're looking for a more rigorously correct $$$dp$$$, it would look something like this.</p> <div class="spoiler"><b class="spoiler-title">Proof</b><div class="spoiler-content" style="display: none;"><p>Let $$$dp_{i, j, S}$$$ denote the probability of reaching some node $$$i$$$ distance away before some node $$$j$$$ distance away where $$$S$$$ is a representation of the entire state of of the process (not necessarily an integer). I think you already understood why we can assume the $$$lca$$$ is already reached. We aim to show that $$$S$$$ does not matter in our calculation. Assume inductively that $$$S$$$ does not matter. So, we can assume that states $$$(i-1, j)$$$ and states $$$(i, j-1)$$$ are irrelevant to $$$S$$$. Hence, the part we need to care about is $$$(1-2p) dp_{i, j, S \rightarrow S_a}$$$. A way of thinking about this part of the transition is moving through the collection of $$$S$$$ with the state $$$(i, j)$$$. Obviously, the $$$dp$$$ is a $$$DAG$$$ because no state $$$S$$$ can reach another. Each bounce takes a certain probability $$$p$$$ which is just multiplied in the current path. So, for each state $$$S$$$ with state $$$(i, j)$$$, we have a certain probability to reach it by simply calculating $$$dp$$$ along a DAG as is traditional. Then, from those states of $$$(i, j)$$$ you transition to $$$(i, j-1)$$$ with an equal probability $$$(i-1, j)$$$. So, they have to be equal. Finally, this argument holds for any initial state $$$S$$$ that you reach, so we can conclude that, from any state $$$S$$$ with a state of $$$(i, j)$$$, the probability of transitions to $$$(i-1, j)$$$ and $$$(i, j-1)$$$ are always exactly $$$0.5$$$.</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-809399 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809399 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809399"> <li> <div class="comment"> <table class="comment-table" commentId="809701" commentParentId="809399"> <tr> <td class="left"> <div style="position: absolute; left: 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/AquaBlaze" style="position: relative;"> <img src='https://userpic.codeforces.org/756639/avatar/97d40da74d642a88.jpg'/> </a> <div><a href="/profile/AquaBlaze" title="Master AquaBlaze" class="rated-user user-orange">AquaBlaze</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:21">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809701" href="?#comment-809701" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809399" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809701" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="756639" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809701"> <div class="moveup"> <div class="ttypography"><p>I see, thank you so much!</p></div> </div> </div> <div class="reply info"> <a class="comment-809701 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809701 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809701"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809298" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/satyam_singh93" style="position: relative;"> <img src='https://userpic.codeforces.org/1763011/avatar/9d9fa405de19ab0e.jpg'/> </a> <div><a href="/profile/satyam_singh93" title="Newbie satyam_singh93" class="rated-user user-gray">satyam_singh93</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:04">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809298" href="?#comment-809298" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809298" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1763011" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809298"> <div class="moveup"> <div class="ttypography"><p>I am getting wrong ans . could someone tell me where the code make differene ( [yestrday competiton problem .</p><p>`](<a href="https://codeforces.com/contest/1541/problem/B)">https://codeforces.com/contest/1541/problem/B)</a>.</p> <pre><code>int main( ) { clock_t begin = clock(); file_i_o(); // Write your code here.... int t; cin&gt;&gt;t; while(t-- ){ int n; cin&gt;&gt;n; vector&lt;pair&lt;int,int&gt;&gt;v; v.push_back({0,0}); loop(i,0,n) { int x; cin&gt;&gt;x; v.pb({x,i+1}); } sort(v.begin()+1,v.end()); int count =0; for(int i=1 ; i&lt;=n;i++) { for(ll j=i+1;j&lt;=n;j++) { ll left = v[i].first * v[j].first; ll right = v[i].second + v[j].second; if(left == right) count++; if(left &gt; 2*n ) break; } } cout&lt;&lt;count&lt;&lt;endl; } </code></pre></div> </div> </div> <div class="reply info"> <a class="comment-809298 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809298 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809298"> <li> <div class="comment"> <table class="comment-table" commentId="809305" commentParentId="809298"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:16">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809305" href="?#comment-809305" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809298" style="font-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="809305" 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="809305" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809305"> <div class="moveup"> <div class="ttypography"><p>v[i].first * v[j].first can create overflow. So, you need to convert them to long long by using</p><p>ll left = 1LL * v[i].first * v[j].first;</p><p>instead and it would pass.</p><p>(Simply save the value in long long won't help. You need to convert them to long long before doing multiplication. 1LL* is one way)</p></div> </div> </div> <div class="reply info"> <a class="comment-809305 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809305 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809305"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809309" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809309" href="?#comment-809309" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809309" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809309"> <div class="moveup"> <div class="ttypography"><p>Hi, in problem Div1.B/Div2.D; I can't wrap my head around $$$F[x][y]=F[x−1][y]/2+F[x][y−1]/2$$$. Why is it not $$$F[x][y]=F[x−1][y+1]/2+F[x+1][y−1]/2$$$, can someone please explain to me why is my transition wrong and/or why is the aforementioned transition correct? </p></div> </div> </div> <div class="reply info"> <a class="comment-809309 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809309 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809309"> <li> <div class="comment"> <table class="comment-table" commentId="809311" commentParentId="809309"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:32">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809311" href="?#comment-809311" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809309" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809311" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809311"> <div class="moveup"> <div class="ttypography"><p>x and y is the distance left for each side right? So, if you take one out, it won't make sense to add that one to the other side since the distance should be either x-1 and y or x and y-1.</p></div> </div> </div> <div class="reply info"> <a class="comment-809311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809311"> <li> <div class="comment"> <table class="comment-table" commentId="809339" commentParentId="809311"> <tr> <td class="left"> <div style="position: absolute; left: 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/me3tazzzz" style="position: relative;"> <img src='https://userpic.codeforces.org/829925/avatar/b391ce71330ce919.jpg'/> </a> <div><a href="/profile/me3tazzzz" title="Expert me3tazzzz" class="rated-user user-blue">me3tazzzz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 16:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809339" href="?#comment-809339" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809339" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="829925" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809339"> <div class="moveup"> <div class="ttypography"><p>Thank you so much I understand. I had a minor misunderstanding of the parameters to the dp state.</p></div> </div> </div> <div class="reply info"> <a class="comment-809339 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809339 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809339"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809371" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:13">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809371" href="?#comment-809371" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809371" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809371"> <div class="moveup"> <div class="ttypography"><p>PLease explain why 2 same codes are not giving the same ans</p><p>code forces round 728 div2<br />Problem B :<a href="https://codeforces.com/contest/1541/problem/B">https://codeforces.com/contest/1541/problem/B</a></p><p>AC Submission : <a href="https://ide.codingblocks.com/s/579769">https://ide.codingblocks.com/s/579769</a></p><p>Wrong output Submission :<a href="https://ide.codingblocks.com/s/579771">https://ide.codingblocks.com/s/579771</a></p><p>Difference is using of macro (node) instead of pair&lt;int,int&gt; </p><p>Please help</p></div> </div> </div> <div class="reply info"> <a class="comment-809371 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809371 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809371"> <li> <div class="comment"> <table class="comment-table" commentId="809379" commentParentId="809371"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/VasuOberoi" style="position: relative;"> <img src='https://userpic.codeforces.org/1720103/avatar/dba3a23afa4b323e.jpg'/> </a> <div><a href="/profile/VasuOberoi" title="Specialist VasuOberoi" class="rated-user user-cyan">VasuOberoi</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 18:29">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809379" href="?#comment-809379" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809371" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809379" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1720103" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809379"> <div class="moveup"> <div class="ttypography"><p>If i am using #define node pair&lt;int,int&gt; it is getting accepted but when i am using typedef pair&lt;int,int&gt; node; it is giving wrong answer</p><p>Why this is happening ?? Is it a bug??</p></div> </div> </div> <div class="reply info"> <a class="comment-809379 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809379 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809379"> <li> <div class="comment"> <table class="comment-table" commentId="809407" commentParentId="809379"> <tr> <td class="left"> <div style="position: absolute; left: 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/LUL____SEPLED1305" style="position: relative;"> <img src='https://userpic.codeforces.org/843012/avatar/b6851644302923fd.jpg'/> </a> <div><a href="/profile/LUL____SEPLED1305" title="Master LUL____SEPLED1305" class="rated-user user-orange">LUL____SEPLED1305</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/26/2021 19:01">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809407" href="?#comment-809407" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809379" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809407" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="843012" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809407"> <div class="moveup"> <div class="ttypography"><p>Not really sure why this is happening.</p><p>However, I think the problem is the position of #define int long long. So, for #define pair&lt;int,int&gt; node it seems that compiler change node -&gt; pair&lt;int,int&gt; -&gt; pair&lt;long long, long long&gt;. However, when you do typedef, it still keeps in pair&lt;int, int&gt; which creates an overflow problem later on. </p><p>I did try moving #define int long long up above typedef and the code pass. So, my best guess is #define int long long only replace int after that position with long long. Thus, node is still pair&lt;int, int&gt; in the typedef solution, while node is changed to pair&lt;long long, long long&gt; in the second solution.</p></div> </div> </div> <div class="reply info"> <a class="comment-809407 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809407 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809407"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809627" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:23">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809627" href="?#comment-809627" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809627" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809627"> <div class="moveup"> <div class="ttypography"><p>May I ask why in the Div1D solution ci=i-bi, I think it should be ci=bi ...</p></div> </div> </div> <div class="reply info"> <a class="comment-809627 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809627 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809627"> <li> <div class="comment"> <table class="comment-table" commentId="809631" commentParentId="809627"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:44">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809631" href="?#comment-809631" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809627" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809631" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809631"> <div class="moveup"> <div class="ttypography"><p>Check the definition of bi again dude. bi here means <strong>number of elements greater than pi</strong>. So to get ci, which is <strong>number of elements smaller than pi</strong>, you need i-bi.</p></div> </div> </div> <div class="reply info"> <a class="comment-809631 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809631 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809631"> <li> <div class="comment"> <table class="comment-table" commentId="809636" commentParentId="809631"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 15:58">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809636" href="?#comment-809636" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809631" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809636" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809636"> <div class="moveup"> <div class="ttypography"><p>I read it again. If I read it correctly, bi stands for j&lt;i,pj&gt;pi, and ci stands for j&gt;i,pj&lt;pi. For example, p={1,3,5,4,6,2}, I think b4=1,c4=1, please point out my problem</p></div> </div> </div> <div class="reply info"> <a class="comment-809636 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809636 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809636"> <li> <div class="comment"> <table class="comment-table" commentId="809638" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809638" href="?#comment-809638" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809638" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809638"> <div class="moveup"> <div class="ttypography"><p>oh, the array index starts from 1</p></div> </div> </div> <div class="reply info"> <a class="comment-809638 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809638 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809638"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="809639" commentParentId="809636"> <tr> <td class="left"> <div style="position: absolute; left: 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/Sigh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Sigh" title="Expert Sigh" class="rated-user user-blue">Sigh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809639" href="?#comment-809639" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809636" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809639" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="222972" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-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-809639"> <div class="moveup"> <div class="ttypography"><p>You are right.</p><p>I guess it might just be typo and ci stands for j&lt;i, pj&lt;pi. At least with this definition of ci the algorithm seems correct :)</p></div> </div> </div> <div class="reply info"> <a class="comment-809639 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809639 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809639"> <li> <div class="comment"> <table class="comment-table" commentId="809641" commentParentId="809639"> <tr> <td class="left"> <div style="position: absolute; left: 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/newbiewzs" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/newbiewzs" title="International Master newbiewzs" class="rated-user user-orange">newbiewzs</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 16:05">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809641" href="?#comment-809641" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809639" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809641" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1845523" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809641"> <div class="moveup"> <div class="ttypography"><p>thanks!</p></div> </div> </div> <div class="reply info"> <a class="comment-809641 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809641 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809641"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809705" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/darthrevenge" style="position: relative;"> <img src='https://userpic.codeforces.org/1567000/avatar/ee31d2a91a9575b9.jpg'/> </a> <div><a href="/profile/darthrevenge" title="Candidate Master darthrevenge" class="rated-user user-violet">darthrevenge</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2021 19:52">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809705" href="?#comment-809705" style="font-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="809705" revisionCount="4" revision="4"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">4</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="809705" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1567000" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809705"> <div class="moveup"> <div class="ttypography"><p>Here's my solution of B div 1 / D div 2 without LCA, using single DFS per node. <a href="/contest/1540/submission/120700765" title="Посылка 120700765 от darthrevenge">120700765</a> It is similar to what <a class="rated-user user-violet" href="/profile/OleschY" title="Кандидат в мастера OleschY">OleschY</a> suggested above. I've tried to describe it in the <a href="https://codeforces.com/blog/entry/92284">blog</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-809705 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809705 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809705"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="809951" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 21:33">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809951" href="?#comment-809951" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809951" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809951"> <div class="moveup"> <div class="ttypography"><p>Can someone explain how you can find the LCA for each pair so quick? Iterating through every root is and then considering every pair is already N^3</p></div> </div> </div> <div class="reply info"> <a class="comment-809951 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809951 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809951"> <li> <div class="comment"> <table class="comment-table" commentId="809965" commentParentId="809951"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/PurpleCrayon" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/PurpleCrayon" title="International Grandmaster PurpleCrayon" class="rated-user user-red">PurpleCrayon</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:36">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809965" href="?#comment-809965" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809951" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809965" class="CommentVoteFrame" data-commentRating="25" data-commentUserId="1604355" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:green;font-weight:bold;">+25</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809965"> <div class="moveup"> <div class="ttypography"><p>There are a couple ways you could do it:</p> <ol> <li>Just use standard binary lifting (initialize once for each root). This runs in $$$\mathcal{O}(n^3 \log{}n)$$$, and should pass under the given constraints. You could also just use $$$\mathcal{O}(1)$$$ lca using an rmq over an euler tour.</li> <li>You could use a version of dp, where $$$dp[a][b] = lca(a, b)$$$. If the depth of $$$a$$$ is greater than the depth of $$$b$$$, $$$dp[a][b] = dp[parent[a]][b]$$$, otherwise $$$dp[a][b] = dp[a][parent[b]]$$$. The base cases are $$$dp[a][a] = a$$$ for all $$$a$$$. This runs in $$$\mathcal{O}(n^3)$$$.</li> <li>You could extend this idea and do the main solution's dp directly on the tree (without ever worrying about lca's). The recurrence is equivalent to the main solution ($$$dp[a][b] = \frac{dp[parent[a]][b]+dp[a][parent[b]]}{2}$$$ with the base cases being one node is an ancestor of the other.</li> </ol></div> </div> </div> <div class="reply info"> <a class="comment-809965 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809965 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809965"> <li> <div class="comment"> <table class="comment-table" commentId="809967" commentParentId="809965"> <tr> <td class="left"> <div style="position: absolute; left: 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/dulatcodes" style="position: relative;"> <img src='https://userpic.codeforces.org/925858/avatar/d62e7d14273c3981.jpg'/> </a> <div><a href="/profile/dulatcodes" title="Expert dulatcodes" class="rated-user user-blue">dulatcodes</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/28/2021 22:47">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-809967" href="?#comment-809967" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-809965" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="809967" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="925858" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-809967"> <div class="moveup"> <div class="ttypography"><p>Thank you so much for the detailed answer!</p></div> </div> </div> <div class="reply info"> <a class="comment-809967 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-809967 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-809967"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="810320" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Anurag_20" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/Anurag_20" title="Specialist Anurag_20" class="rated-user user-cyan">Anurag_20</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/30/2021 19:02">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-810320" href="?#comment-810320" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="810320" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1600346" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-810320"> <div class="moveup"> <div class="ttypography"><p>O(n2) is also working for div2 C Great Graphs. <a href="https://codeforces.com/contest/1540/submission/120964787">https://codeforces.com/contest/1540/submission/120964787</a></p></div> </div> </div> <div class="reply info"> <a class="comment-810320 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-810320 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-810320"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="813828" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/T404" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/T404" title="Master T404" class="rated-user user-orange">T404</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jul/09/2021 19:31">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-813828" href="?#comment-813828" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="813828" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="523287" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-813828"> <div class="moveup"> <div class="ttypography"><p>Div1D can be done in $$$O(n \sqrt{n})$$$. We can use square root decomposition to replace all BITs in tutorial. Since a value in a non-updated position changes by at most one and all values change in the same direction, the full recomputation is only needed in the updated position and we can perform an incremental change in $$$O(1)$$$ for values in each non-updated positions.</p><p><a href="https://codeforces.com/contest/1540/submission/121831547">Code</a></p></div> </div> </div> <div class="reply info"> <a class="comment-813828 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-813828 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-813828"> <li> <div class="comment"> <table class="comment-table" commentId="834051" commentParentId="813828"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/KeyID" style="position: relative;"> <img src='https://userpic.codeforces.org/226684/avatar/10e3671716bf6859.jpg'/> </a> <div><a href="/profile/KeyID" title="Grandmaster KeyID" class="rated-user user-red">KeyID</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Aug/29/2021 12:42">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-834051" href="?#comment-834051" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-813828" style="font-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="834051" 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="834051" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="226684" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-834051"> <div class="moveup"> <div class="ttypography"><p>Realy impressive solution. I'm surprised no stars were given to you until me. Maybe many people didn't get your idea since the solution is actually much more complicated than your brief comment(at least in my opinion). I also wrote a piece of code which used your method but simplified a small part of steps. <a href="https://codeforces.com/contest/1540/submission/127317031">Here</a> it is.</p></div> </div> </div> <div class="reply info"> <a class="comment-834051 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-834051 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-834051"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="837924" commentParentId="-1"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Harolinch" style="position: relative;"> <img src='https://userpic.codeforces.org/427341/avatar/cf8608aeb55edc95.jpg'/> </a> <div><a href="/profile/Harolinch" title="Pupil Harolinch" class="rated-user user-green">Harolinch</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:10">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837924" href="?#comment-837924" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837924" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="427341" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837924"> <div class="moveup"> <div class="ttypography"><p><a class="rated-user user-orange" href="/profile/ijxjdjd" title="Мастер ijxjdjd">ijxjdjd</a> in problem Tree array you said that Fixing a given root r, the expected value of the entire process is obviously the sum of the expected values for a fixed root divided by n.</p><p>why we divide by n at the end ? </p></div> </div> </div> <div class="reply info"> <a class="comment-837924 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837924 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837924"> <li> <div class="comment"> <table class="comment-table" commentId="837928" commentParentId="837924"> <tr> <td class="left"> <div style="position: absolute; left: 0;" class="comment-indent-holder"> <div class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ijxjdjd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/ijxjdjd" title="Master ijxjdjd" class="rated-user user-orange">ijxjdjd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2021 07:41">2 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-837928" href="?#comment-837928" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-837924" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="837928" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="723705" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-voteup-blue.png" alt="Vote: I like it" title="Vote: I like it"/></a> <span class="commentRating"><span style="color:gray;font-weight:bold;">0</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-837928"> <div class="moveup"> <div class="ttypography"><p>The calculation is independent based on whichever node that you choose first (it becomes the “root”). Initially you choose one of $$$n$$$ nodes with equal probability so you divide by $$$n$$$ at the end after you’ve summed up the independent expected value after choosing the node $$$i$$$ initially.</p></div> </div> </div> <div class="reply info"> <a class="comment-837928 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-837928 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-837928"> </ul> </div> </li> </ul> </div> <br/> <div id="editBox-100805" 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 firstPreview100805 = true; var lastPreviewContent100805 = ''; 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=100805] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=100805] 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-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-92809").click(function () { $.post("/data/topic/vote", {topicId: 92809, _tta: Codeforces.tta(), topicRevisionId: 230372, 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:33:28</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:'81289372dffb0c4e',t:'MTY5NjcwNzIwOC45MzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1542A
1542
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>Вам дано мультимножество (то есть множество, которое может содержать несколько одинаковых элементов), содержащее $$$2n$$$ целых чисел. Определите, возможно ли разбить его ровно на $$$n$$$ пар (каждый элемент должен присутствовать ровно в одной паре) так, чтобы сумма элементов в каждой паре была <span class="tex-font-style-bf">нечётна</span> (то есть при делении на $$$2$$$ давала остаток $$$1$$$).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит одно целое число $$$t$$$ ($$$1\leq t\leq 100$$$) – количество наборов входных данных. Далее следует описание наборов входных данных.</p><p>Первая строка каждого набора содержит одно целое число $$$n$$$ ($$$1\leq n\leq 100$$$)</p><p>Вторая строка каждого набора содержит $$$2n$$$ целых чисел $$$a_1,a_2,\dots, a_{2n}$$$ ($$$0\leq a_i\leq 100$$$) — числа в множестве.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">Yes</span>», если множество можно разбить ровно на $$$n$$$ пар таких, что сумма элементов в каждой паре <span class="tex-font-style-bf">нечётна</span>, и «<span class="tex-font-style-tt">No</span>» иначе. Вы можете выводить каждую букву в любом регистре (строчную или заглавную).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 2 2 3 4 5 3 2 3 4 5 5 5 1 2 4 1 2 3 4 1 5 3 2 6 7 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes No No Yes No </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных возможно следующее разбиение множества: $$$(2,3)$$$, $$$(4,5)$$$.</p><p>Во втором, третьем и пятом наборах можно показать, что разбиение невозможно.</p><p>В четвертом наборе возможно следующее разбиение множества: $$$(2,3)$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="1bbe190c5133b73581ba56d3ba1d6354"/> <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="cc177b9c6a05bb6a147cd70438fe0a003547d1ac"/> <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='1bbe190c5133b73581ba56d3ba1d6354'>&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%2F1542%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='1bbe190c5133b73581ba56d3ba1d6354'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1542">Codeforces Round 729 (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='1bbe190c5133b73581ba56d3ba1d6354'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1542/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *800 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1bbe190c5133b73581ba56d3ba1d6354'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1034809"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1bbe190c5133b73581ba56d3ba1d6354'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1034809"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92410" title="Codeforces Round #729 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13966" resourceName="Codeforces Round #729 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/92492" title="Tutorial of Codeforces Round 729 (Div.2)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13973" resourceName="Tutorial of Codeforces Round 729 (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> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1542">Задачи</a></li> <li><a href="/contest/1542/submit">Отослать</a></li> <li><a href="/contest/1542/my">Мои посылки</a></li> <li><a href="/contest/1542/status">Статус</a></li> <li><a href="/contest/1542/hacks">Взломы</a></li> <li><a href="/contest/1542/room/1">Комната</a></li> <li><a href="/contest/1542/standings">Положение</a></li> <li><a href="/contest/1542/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b59bc852fbcba5e435fba6d661e6152e490d85f8"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Вам дано мультимножество (то есть множество, которое может содержать несколько одинаковых элементов), содержащее $$$2n$$$ целых чисел. Определите, возможно ли разбить его ровно на $$$n$$$ пар (каждый элемент должен присутствовать ровно в одной паре) так, чтобы сумма элементов в каждой паре была <span class="tex-font-style-bf">нечётна</span> (то есть при делении на $$$2$$$ давала остаток $$$1$$$).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит одно целое число $$$t$$$ ($$$1\leq t\leq 100$$$) – количество наборов входных данных. Далее следует описание наборов входных данных.</p><p>Первая строка каждого набора содержит одно целое число $$$n$$$ ($$$1\leq n\leq 100$$$)</p><p>Вторая строка каждого набора содержит $$$2n$$$ целых чисел $$$a_1,a_2,\dots, a_{2n}$$$ ($$$0\leq a_i\leq 100$$$) — числа в множестве.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">Yes</span>», если множество можно разбить ровно на $$$n$$$ пар таких, что сумма элементов в каждой паре <span class="tex-font-style-bf">нечётна</span>, и «<span class="tex-font-style-tt">No</span>» иначе. Вы можете выводить каждую букву в любом регистре (строчную или заглавную).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 2 2 3 4 5 3 2 3 4 5 5 5 1 2 4 1 2 3 4 1 5 3 2 6 7 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes No No Yes No </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных возможно следующее разбиение множества: $$$(2,3)$$$, $$$(4,5)$$$.</p><p>Во втором, третьем и пятом наборах можно показать, что разбиение невозможно.</p><p>В четвертом наборе возможно следующее разбиение множества: $$$(2,3)$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c724492b2de7',t:'MTY5NjY2NzM4Mi41ODIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*800"]
1542B
1542
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>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дано бесконечное множество, сгенерированное следующим образом:</p><ul> <li> $$$1$$$ принадлежит множеству. </li><li> Если $$$x$$$ принадлежит множеству, то $$$x \cdot a$$$ и $$$x+b$$$ также принадлежат множеству. </li></ul><p>Например, если $$$a=3$$$ и $$$b=6$$$, то первые пять элементов множества равны:</p><ul> <li> $$$1$$$, </li><li> $$$3$$$ ($$$1$$$ лежит в множестве, поэтому $$$1\cdot a=3$$$ лежит в множестве), </li><li> $$$7$$$ ($$$1$$$ лежит в множестве, поэтому $$$1+b=7$$$ лежит в множестве), </li><li> $$$9$$$ ($$$3$$$ лежит в множестве, поэтому $$$3\cdot a=9$$$ лежит в множестве), </li><li> $$$13$$$ ($$$7$$$ лежит в множестве, поэтому $$$7+b=13$$$ лежит в множестве). </li></ul><p>Даны положительные целые числа $$$a$$$, $$$b$$$, $$$n$$$. Выясните, принадлежит ли $$$n$$$ множеству.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит одно целое число $$$t$$$ ($$$1\leq t\leq 10^5$$$) – количество наборов входных данных. Далее следует описание наборов входных данных.</p><p>Строка, описывающая набор входных данных содержит три целых числа $$$n$$$, $$$a$$$, $$$b$$$ ($$$1\leq n,a,b\leq 10^9$$$), разделенных пробелом.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">Yes</span>», если $$$n$$$ принадлежит множеству, и «<span class="tex-font-style-tt">No</span>» иначе. Вы можете выводить каждую букву в любом регистре (строчную или заглавную).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 24 3 5 10 3 6 2345 1 4 19260817 394 485 19260817 233 264 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes No Yes No Yes </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе $$$24$$$ генерируется следующим образом: </p><ul> <li> $$$1$$$ лежит в множестве, поэтому $$$3$$$ и $$$6$$$ лежат в множестве; </li><li> $$$3$$$ лежит в множестве, поэтому $$$9$$$ и $$$8$$$ лежат в множестве; </li><li> $$$8$$$ лежит в множестве, поэтому $$$24$$$ и $$$13$$$ лежат в множестве. </li></ul><p>Таким образом, $$$24$$$ принадлежит множеству. </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="5773cb643e66325750e9ed2fc9e9085d"/> <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="cc177b9c6a05bb6a147cd70438fe0a003547d1ac"/> <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='5773cb643e66325750e9ed2fc9e9085d'>&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%2F1542%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='5773cb643e66325750e9ed2fc9e9085d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1542">Codeforces Round 729 (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='5773cb643e66325750e9ed2fc9e9085d'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1542/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='5773cb643e66325750e9ed2fc9e9085d'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1034810"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5773cb643e66325750e9ed2fc9e9085d'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1034810"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92410" title="Codeforces Round #729 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13966" resourceName="Codeforces Round #729 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/92492" title="Tutorial of Codeforces Round 729 (Div.2)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13973" resourceName="Tutorial of Codeforces Round 729 (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> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1542">Задачи</a></li> <li><a href="/contest/1542/submit">Отослать</a></li> <li><a href="/contest/1542/my">Мои посылки</a></li> <li><a href="/contest/1542/status">Статус</a></li> <li><a href="/contest/1542/hacks">Взломы</a></li> <li><a href="/contest/1542/room/1">Комната</a></li> <li><a href="/contest/1542/standings">Положение</a></li> <li><a href="/contest/1542/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_4c6cc0f6200c3fff16351ee93185fdfead9a83d6"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дано бесконечное множество, сгенерированное следующим образом:</p><ul> <li> $$$1$$$ принадлежит множеству. </li><li> Если $$$x$$$ принадлежит множеству, то $$$x \cdot a$$$ и $$$x+b$$$ также принадлежат множеству. </li></ul><p>Например, если $$$a=3$$$ и $$$b=6$$$, то первые пять элементов множества равны:</p><ul> <li> $$$1$$$, </li><li> $$$3$$$ ($$$1$$$ лежит в множестве, поэтому $$$1\cdot a=3$$$ лежит в множестве), </li><li> $$$7$$$ ($$$1$$$ лежит в множестве, поэтому $$$1+b=7$$$ лежит в множестве), </li><li> $$$9$$$ ($$$3$$$ лежит в множестве, поэтому $$$3\cdot a=9$$$ лежит в множестве), </li><li> $$$13$$$ ($$$7$$$ лежит в множестве, поэтому $$$7+b=13$$$ лежит в множестве). </li></ul><p>Даны положительные целые числа $$$a$$$, $$$b$$$, $$$n$$$. Выясните, принадлежит ли $$$n$$$ множеству.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит одно целое число $$$t$$$ ($$$1\leq t\leq 10^5$$$) – количество наборов входных данных. Далее следует описание наборов входных данных.</p><p>Строка, описывающая набор входных данных содержит три целых числа $$$n$$$, $$$a$$$, $$$b$$$ ($$$1\leq n,a,b\leq 10^9$$$), разделенных пробелом.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">Yes</span>», если $$$n$$$ принадлежит множеству, и «<span class="tex-font-style-tt">No</span>» иначе. Вы можете выводить каждую букву в любом регистре (строчную или заглавную).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 24 3 5 10 3 6 2345 1 4 19260817 394 485 19260817 233 264 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes No Yes No Yes </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе $$$24$$$ генерируется следующим образом: </p><ul> <li> $$$1$$$ лежит в множестве, поэтому $$$3$$$ и $$$6$$$ лежат в множестве; </li><li> $$$3$$$ лежит в множестве, поэтому $$$9$$$ и $$$8$$$ лежат в множестве; </li><li> $$$8$$$ лежит в множестве, поэтому $$$24$$$ и $$$13$$$ лежат в множестве. </li></ul><p>Таким образом, $$$24$$$ принадлежит множеству. </p><p>Первые пять элементов множества из второго набора входных данных описаны в условии. Можно заметить, что $$$10$$$ не в их числе.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c72cec2b16fe',t:'MTY5NjY2NzM4My45NDQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1500"]
1542C
1542
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>Положим $$$f(i)$$$ равным наименьшему положительному целому числу $$$x$$$ такому, что $$$x$$$ <span class="tex-font-style-bf">не</span> является делителем $$$i$$$.</p><p>Посчитайте $$$\sum_{i=1}^n f(i)$$$ по модулю $$$10^9+7$$$. Иными словами, посчитайте $$$f(1)+f(2)+\dots+f(n)$$$ по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит одно целое число $$$t$$$ ($$$1\leq t\leq 10^4$$$) – количество наборов входных данных. Далее следует описание $$$t$$$ наборов входных данных.</p><p>Каждая строка, описывающая набор входных данных, содержит единственное целое число $$$n$$$ ($$$1\leq n\leq 10^{16}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите единственное целое число $$$ans$$$, где $$$ans=\sum_{i=1}^n f(i)$$$ по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 1 2 3 4 10 10000000000000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 5 7 10 26 366580019 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В четвертом наборе $$$n=4$$$, поэтому $$$ans=f(1)+f(2)+f(3)+f(4)$$$.</p><ul> <li> $$$1$$$ делит $$$1$$$, но $$$2$$$ – не делит, поэтому $$$2$$$ является наименьшим положительным целым числом, которое не делит $$$1$$$. Таким образом, $$$f(1)=2$$$. </li><li> $$$1$$$ и $$$2$$$ делят $$$2$$$, но $$$3$$$ – не делит, поэтому $$$3$$$ является наименьшим положительным целым числом, которое не делит $$$2$$$. Таким образом, $$$f(2)=3$$$. </li><li> $$$1$$$ делит $$$3$$$, но $$$2$$$ – не делит, поэтому $$$2$$$ является наименьшим положительным целым числом, которое не делит $$$3$$$. Таким образом, $$$f(3)=2$$$. </li><li> $$$1$$$ и $$$2$$$ делят $$$4$$$, но $$$3$$$ – не делит, поэтому $$$3$$$ является наименьшим положительным целым числом, которое не делит $$$4$$$. Таким образом, $$$f(4)=3$$$. </li></ul><p>Получаем: $$$ans=f(1)+f(2)+f(3)+f(4)=2+3+2+3=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="294269631b83832fae9cdfaf45760cfa"/> <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="cc177b9c6a05bb6a147cd70438fe0a003547d1ac"/> <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='294269631b83832fae9cdfaf45760cfa'>&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%2F1542%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='294269631b83832fae9cdfaf45760cfa'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1542">Codeforces Round 729 (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='294269631b83832fae9cdfaf45760cfa'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1542/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='294269631b83832fae9cdfaf45760cfa'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1034811"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='294269631b83832fae9cdfaf45760cfa'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1034811"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92410" title="Codeforces Round #729 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13966" resourceName="Codeforces Round #729 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/92492" title="Tutorial of Codeforces Round 729 (Div.2)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13973" resourceName="Tutorial of Codeforces Round 729 (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> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1542">Задачи</a></li> <li><a href="/contest/1542/submit">Отослать</a></li> <li><a href="/contest/1542/my">Мои посылки</a></li> <li><a href="/contest/1542/status">Статус</a></li> <li><a href="/contest/1542/hacks">Взломы</a></li> <li><a href="/contest/1542/room/1">Комната</a></li> <li><a href="/contest/1542/standings">Положение</a></li> <li><a href="/contest/1542/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2819b094a27047f5b13853c7af6c87331fec7da8"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Положим $$$f(i)$$$ равным наименьшему положительному целому числу $$$x$$$ такому, что $$$x$$$ <span class="tex-font-style-bf">не</span> является делителем $$$i$$$.</p><p>Посчитайте $$$\sum_{i=1}^n f(i)$$$ по модулю $$$10^9+7$$$. Иными словами, посчитайте $$$f(1)+f(2)+\dots+f(n)$$$ по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит одно целое число $$$t$$$ ($$$1\leq t\leq 10^4$$$) – количество наборов входных данных. Далее следует описание $$$t$$$ наборов входных данных.</p><p>Каждая строка, описывающая набор входных данных, содержит единственное целое число $$$n$$$ ($$$1\leq n\leq 10^{16}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите единственное целое число $$$ans$$$, где $$$ans=\sum_{i=1}^n f(i)$$$ по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 1 2 3 4 10 10000000000000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 5 7 10 26 366580019 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В четвертом наборе $$$n=4$$$, поэтому $$$ans=f(1)+f(2)+f(3)+f(4)$$$.</p><ul> <li> $$$1$$$ делит $$$1$$$, но $$$2$$$ – не делит, поэтому $$$2$$$ является наименьшим положительным целым числом, которое не делит $$$1$$$. Таким образом, $$$f(1)=2$$$. </li><li> $$$1$$$ и $$$2$$$ делят $$$2$$$, но $$$3$$$ – не делит, поэтому $$$3$$$ является наименьшим положительным целым числом, которое не делит $$$2$$$. Таким образом, $$$f(2)=3$$$. </li><li> $$$1$$$ делит $$$3$$$, но $$$2$$$ – не делит, поэтому $$$2$$$ является наименьшим положительным целым числом, которое не делит $$$3$$$. Таким образом, $$$f(3)=2$$$. </li><li> $$$1$$$ и $$$2$$$ делят $$$4$$$, но $$$3$$$ – не делит, поэтому $$$3$$$ является наименьшим положительным целым числом, которое не делит $$$4$$$. Таким образом, $$$f(4)=3$$$. </li></ul><p>Получаем: $$$ans=f(1)+f(2)+f(3)+f(4)=2+3+2+3=10$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c735596d1610',t:'MTY5NjY2NzM4NS4zNjcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1600"]
1542D
1542
D
ru
D. Очередь с приоритетом
<div class="problem-statement"><div class="header"><div class="title">D. Очередь с приоритетом</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дана последовательность $$$A$$$, в которой каждый элемент записан в формате <span class="tex-font-style-tt">+ x</span> или <span class="tex-font-style-tt">-</span>, где $$$x$$$ — целое число.</p><p>Для последовательности $$$S$$$, в которой каждый элемент записан в формате <span class="tex-font-style-tt">+ x</span> или <span class="tex-font-style-tt">-</span>, определим $$$f(S)$$$ следующим образом:</p><ul> <li> Проходим по $$$S$$$ от первого элемента до последнего и поддерживаем мультимножество $$$T$$$, изначально пустое. </li><li> Если элемент последовательности имеет вид <span class="tex-font-style-tt">+ x</span>, добавим $$$x$$$ в $$$T$$$. Иначе удалим наименьший элемент из $$$T$$$ (если $$$T$$$ пусто, ничего делать не нужно). </li><li> После прохода по $$$S$$$ посчитаем сумму всех элементов в $$$T$$$. $$$f(S)$$$ полагается равным этой сумме. </li></ul><p>Последовательность $$$b$$$ является подпоследовательностью последовательности $$$a$$$, если $$$b$$$ может быть получена из $$$a$$$ удалением нуля или больше элементов без изменения порядка оставшихся элементов. Для всех подпоследовательностей $$$B$$$ последовательности $$$A$$$ посчитайте сумму $$$f(B)$$$ по модулю $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$1\leq n\leq 500$$$) – длину $$$A$$$.</p><p>Каждая из следующих $$$n$$$ строк начинается с символа операции <span class="tex-font-style-tt">+</span> или <span class="tex-font-style-tt">-</span>. Если символ равен <span class="tex-font-style-tt">+</span>, то за ним следует целое число $$$x$$$ ($$$1\le x&lt;998\,244\,353$$$). $$$i$$$-я строка из этих $$$n$$$ строк описывает $$$i$$$-й элемент $$$A$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, равное ответу на задачу по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 - + 1 + 2 - </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 16</pre></div><div class="input"><div class="title">Входные данные</div><pre> 15 + 2432543 - + 4567886 + 65638788 - + 578943 - - + 62356680 - + 711111 - + 998244352 - - </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 750759115</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере все возможные пары $$$B$$$ и $$$f(B)$$$ выглядят так:</p><ul> <li> $$$B=$$$ <span class="tex-font-style-tt">{}</span>, $$$f(B)=0$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{-}</span>, $$$f(B)=0$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{+ 1, -}</span>, $$$f(B)=0$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{-, + 1, -}</span>, $$$f(B)=0$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{+ 2, -}</span>, $$$f(B)=0$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{-, + 2, -}</span>, $$$f(B)=0$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{-}</span>, $$$f(B)=0$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{-, -}</span>, $$$f(B)=0$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{+ 1, + 2}</span>, $$$f(B)=3$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{+ 1, + 2, -}</span>, $$$f(B)=2$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{-, + 1, + 2}</span>, $$$f(B)=3$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{-, + 1, + 2, -}</span>, $$$f(B)=2$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{-, + 1}</span>, $$$f(B)=1$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{+ 1}</span>, $$$f(B)=1$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{-, + 2}</span>, $$$f(B)=2$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{+ 2}</span>, $$$f(B)=2$$$. </li></ul><p>Сумма этих значений равна $$$16$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="187f565687ca8037605f624dd1bdd471"/> <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="cc177b9c6a05bb6a147cd70438fe0a003547d1ac"/> <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='187f565687ca8037605f624dd1bdd471'>&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%2F1542%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='187f565687ca8037605f624dd1bdd471'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1542">Codeforces Round 729 (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='187f565687ca8037605f624dd1bdd471'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1542/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Тернарный поиск"> тернарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *2200 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='187f565687ca8037605f624dd1bdd471'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1034812"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='187f565687ca8037605f624dd1bdd471'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1034812"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92410" title="Codeforces Round #729 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13966" resourceName="Codeforces Round #729 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/92492" title="Tutorial of Codeforces Round 729 (Div.2)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13973" resourceName="Tutorial of Codeforces Round 729 (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> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1542">Задачи</a></li> <li><a href="/contest/1542/submit">Отослать</a></li> <li><a href="/contest/1542/my">Мои посылки</a></li> <li><a href="/contest/1542/status">Статус</a></li> <li><a href="/contest/1542/hacks">Взломы</a></li> <li><a href="/contest/1542/room/1">Комната</a></li> <li><a href="/contest/1542/standings">Положение</a></li> <li><a href="/contest/1542/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_046113069e1ea701976fc0cb43119a33af94b79a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Очередь с приоритетом</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дана последовательность $$$A$$$, в которой каждый элемент записан в формате <span class="tex-font-style-tt">+ x</span> или <span class="tex-font-style-tt">-</span>, где $$$x$$$ — целое число.</p><p>Для последовательности $$$S$$$, в которой каждый элемент записан в формате <span class="tex-font-style-tt">+ x</span> или <span class="tex-font-style-tt">-</span>, определим $$$f(S)$$$ следующим образом:</p><ul> <li> Проходим по $$$S$$$ от первого элемента до последнего и поддерживаем мультимножество $$$T$$$, изначально пустое. </li><li> Если элемент последовательности имеет вид <span class="tex-font-style-tt">+ x</span>, добавим $$$x$$$ в $$$T$$$. Иначе удалим наименьший элемент из $$$T$$$ (если $$$T$$$ пусто, ничего делать не нужно). </li><li> После прохода по $$$S$$$ посчитаем сумму всех элементов в $$$T$$$. $$$f(S)$$$ полагается равным этой сумме. </li></ul><p>Последовательность $$$b$$$ является подпоследовательностью последовательности $$$a$$$, если $$$b$$$ может быть получена из $$$a$$$ удалением нуля или больше элементов без изменения порядка оставшихся элементов. Для всех подпоследовательностей $$$B$$$ последовательности $$$A$$$ посчитайте сумму $$$f(B)$$$ по модулю $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$1\leq n\leq 500$$$) – длину $$$A$$$.</p><p>Каждая из следующих $$$n$$$ строк начинается с символа операции <span class="tex-font-style-tt">+</span> или <span class="tex-font-style-tt">-</span>. Если символ равен <span class="tex-font-style-tt">+</span>, то за ним следует целое число $$$x$$$ ($$$1\le x&lt;998\,244\,353$$$). $$$i$$$-я строка из этих $$$n$$$ строк описывает $$$i$$$-й элемент $$$A$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, равное ответу на задачу по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 - + 1 + 2 - </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 16</pre></div><div class="input"><div class="title">Входные данные</div><pre> 15 + 2432543 - + 4567886 + 65638788 - + 578943 - - + 62356680 - + 711111 - + 998244352 - - </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 750759115</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере все возможные пары $$$B$$$ и $$$f(B)$$$ выглядят так:</p><ul> <li> $$$B=$$$ <span class="tex-font-style-tt">{}</span>, $$$f(B)=0$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{-}</span>, $$$f(B)=0$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{+ 1, -}</span>, $$$f(B)=0$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{-, + 1, -}</span>, $$$f(B)=0$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{+ 2, -}</span>, $$$f(B)=0$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{-, + 2, -}</span>, $$$f(B)=0$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{-}</span>, $$$f(B)=0$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{-, -}</span>, $$$f(B)=0$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{+ 1, + 2}</span>, $$$f(B)=3$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{+ 1, + 2, -}</span>, $$$f(B)=2$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{-, + 1, + 2}</span>, $$$f(B)=3$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{-, + 1, + 2, -}</span>, $$$f(B)=2$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{-, + 1}</span>, $$$f(B)=1$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{+ 1}</span>, $$$f(B)=1$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{-, + 2}</span>, $$$f(B)=2$$$. </li><li> $$$B=$$$ <span class="tex-font-style-tt">{+ 2}</span>, $$$f(B)=2$$$. </li></ul><p>Сумма этих значений равна $$$16$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c73e2cfb7a7d',t:'MTY5NjY2NzM4Ni43MTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0422\u0435\u0440\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0442\u0435\u0440\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "*2200"]
1542E1
1542
E1
ru
E1. Аномальные пары перестановок (простая версия)
<div class="problem-statement"><div class="header"><div class="title">E1. Аномальные пары перестановок (простая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это простая версия задачи. Единственное различие между простой и сложной версиями заключается в ограничениях на $$$n$$$. Вы можете делать взломы, только если решили обе версии этой задачи.</span></p><p>Перестановка чисел $$$1, 2, \ldots, n$$$ – это последовательность из $$$n$$$ целых чисел, в которой каждое число от $$$1$$$ до $$$n$$$ встречается ровно один раз. Например, $$$[2,3,1,4]$$$ является перестановкой $$$1, 2, 3, 4$$$, но $$$[1,4,2,2]$$$ – не перестановка, поскольку $$$2$$$ встречается здесь дважды.</p><p>Напомним, что количеством инверсий в перестановке $$$a_1, a_2, \ldots, a_n$$$ называется число пар индексов $$$(i, j)$$$ таких, что $$$i &lt; j$$$ и $$$a_i &gt; a_j$$$.</p><p>Пусть $$$p$$$ и $$$q$$$ – две перестановки чисел $$$1, 2, \ldots, n$$$. Найдите количество пар перестановок $$$(p,q)$$$, удовлетворяющих следующим условиям:</p><ul> <li> $$$p$$$ лексикографически меньше $$$q$$$. </li><li> Количество инверсий в $$$p$$$ больше, чем в $$$q$$$. </li></ul><p>Выведите это количество пар по модулю $$$mod$$$. Обратите внимание, что $$$mod$$$ – не обязательно простое число.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке содержатся два целых числа $$$n$$$ и $$$mod$$$ ($$$1\le n\le 50$$$, $$$1\le mod\le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — ответ на задачу по модулю $$$mod$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 403458273 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 17</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Все возможные пары перестановок $$$(p,q)$$$ при $$$n=4$$$:</p><ul> <li> $$$p=[1,3,4,2]$$$, $$$q=[2,1,3,4]$$$, </li><li> $$$p=[1,4,2,3]$$$, $$$q=[2,1,3,4]$$$, </li><li> $$$p=[1,4,3,2]$$$, $$$q=[2,1,3,4]$$$, </li><li> $$$p=[1,4,3,2]$$$, $$$q=[2,1,4,3]$$$, </li><li> $$$p=[1,4,3,2]$$$, $$$q=[2,3,1,4]$$$, </li><li> $$$p=[1,4,3,2]$$$, $$$q=[3,1,2,4]$$$, </li><li> $$$p=[2,3,4,1]$$$, $$$q=[3,1,2,4]$$$, </li><li> $$$p=[2,4,1,3]$$$, $$$q=[3,1,2,4]$$$, </li><li> $$$p=[2,4,3,1]$$$, $$$q=[3,1,2,4]$$$, </li><li> $$$p=[2,4,3,1]$$$, $$$q=[3,1,4,2]$$$, </li><li> $$$p=[2,4,3,1]$$$, $$$q=[3,2,1,4]$$$, </li><li> $$$p=[2,4,3,1]$$$, $$$q=[4,1,2,3]$$$, </li><li> $$$p=[3,2,4,1]$$$, $$$q=[4,1,2,3]$$$, </li><li> $$$p=[3,4,1,2]$$$, $$$q=[4,1,2,3]$$$, </li><li> $$$p=[3,4,2,1]$$$, $$$q=[4,1,2,3]$$$, </li><li> $$$p=[3,4,2,1]$$$, $$$q=[4,1,3,2]$$$, </li><li> $$$p=[3,4,2,1]$$$, $$$q=[4,2,1,3]$$$. </li></ul></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="cd34d0086f062ff12596a2c475eae0e1"/> <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="cc177b9c6a05bb6a147cd70438fe0a003547d1ac"/> <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='cd34d0086f062ff12596a2c475eae0e1'>&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%2F1542%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='cd34d0086f062ff12596a2c475eae0e1'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1542">Codeforces Round 729 (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='cd34d0086f062ff12596a2c475eae0e1'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1542/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Быстрое преобразование Фурье"> бпф </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *2400 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='cd34d0086f062ff12596a2c475eae0e1'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1034813"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='cd34d0086f062ff12596a2c475eae0e1'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1034813"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92410" title="Codeforces Round #729 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13966" resourceName="Codeforces Round #729 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/92492" title="Tutorial of Codeforces Round 729 (Div.2)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13973" resourceName="Tutorial of Codeforces Round 729 (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> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1542">Задачи</a></li> <li><a href="/contest/1542/submit">Отослать</a></li> <li><a href="/contest/1542/my">Мои посылки</a></li> <li><a href="/contest/1542/status">Статус</a></li> <li><a href="/contest/1542/hacks">Взломы</a></li> <li><a href="/contest/1542/room/1">Комната</a></li> <li><a href="/contest/1542/standings">Положение</a></li> <li><a href="/contest/1542/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c65e660adc799128c124f13d4401632cd4a4ca69"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это простая версия задачи. Единственное различие между простой и сложной версиями заключается в ограничениях на $$$n$$$. Вы можете делать взломы, только если решили обе версии этой задачи.</span></p><p>Перестановка чисел $$$1, 2, \ldots, n$$$ – это последовательность из $$$n$$$ целых чисел, в которой каждое число от $$$1$$$ до $$$n$$$ встречается ровно один раз. Например, $$$[2,3,1,4]$$$ является перестановкой $$$1, 2, 3, 4$$$, но $$$[1,4,2,2]$$$ – не перестановка, поскольку $$$2$$$ встречается здесь дважды.</p><p>Напомним, что количеством инверсий в перестановке $$$a_1, a_2, \ldots, a_n$$$ называется число пар индексов $$$(i, j)$$$ таких, что $$$i &lt; j$$$ и $$$a_i &gt; a_j$$$.</p><p>Пусть $$$p$$$ и $$$q$$$ – две перестановки чисел $$$1, 2, \ldots, n$$$. Найдите количество пар перестановок $$$(p,q)$$$, удовлетворяющих следующим условиям:</p><ul> <li> $$$p$$$ лексикографически меньше $$$q$$$. </li><li> Количество инверсий в $$$p$$$ больше, чем в $$$q$$$. </li></ul><p>Выведите это количество пар по модулю $$$mod$$$. Обратите внимание, что $$$mod$$$ – не обязательно простое число.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке содержатся два целых числа $$$n$$$ и $$$mod$$$ ($$$1\le n\le 50$$$, $$$1\le mod\le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — ответ на задачу по модулю $$$mod$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 403458273 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 17</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Все возможные пары перестановок $$$(p,q)$$$ при $$$n=4$$$:</p><ul> <li> $$$p=[1,3,4,2]$$$, $$$q=[2,1,3,4]$$$, </li><li> $$$p=[1,4,2,3]$$$, $$$q=[2,1,3,4]$$$, </li><li> $$$p=[1,4,3,2]$$$, $$$q=[2,1,3,4]$$$, </li><li> $$$p=[1,4,3,2]$$$, $$$q=[2,1,4,3]$$$, </li><li> $$$p=[1,4,3,2]$$$, $$$q=[2,3,1,4]$$$, </li><li> $$$p=[1,4,3,2]$$$, $$$q=[3,1,2,4]$$$, </li><li> $$$p=[2,3,4,1]$$$, $$$q=[3,1,2,4]$$$, </li><li> $$$p=[2,4,1,3]$$$, $$$q=[3,1,2,4]$$$, </li><li> $$$p=[2,4,3,1]$$$, $$$q=[3,1,2,4]$$$, </li><li> $$$p=[2,4,3,1]$$$, $$$q=[3,1,4,2]$$$, </li><li> $$$p=[2,4,3,1]$$$, $$$q=[3,2,1,4]$$$, </li><li> $$$p=[2,4,3,1]$$$, $$$q=[4,1,2,3]$$$, </li><li> $$$p=[3,2,4,1]$$$, $$$q=[4,1,2,3]$$$, </li><li> $$$p=[3,4,1,2]$$$, $$$q=[4,1,2,3]$$$, </li><li> $$$p=[3,4,2,1]$$$, $$$q=[4,1,2,3]$$$, </li><li> $$$p=[3,4,2,1]$$$, $$$q=[4,1,3,2]$$$, </li><li> $$$p=[3,4,2,1]$$$, $$$q=[4,2,1,3]$$$. </li></ul></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 11:29: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:'8124c746ac1a3a95',t:'MTY5NjY2NzM4OC4wNjQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u043f\u0444", "\u0434\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*2400"]
1542E2
1542
E2
ru
E2. Аномальные пары перестановок (сложная версия)
<div class="problem-statement"><div class="header"><div class="title">E2. Аномальные пары перестановок (сложная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это сложная версия задачи. Единственное различие между простой и сложной версиями заключается в ограничениях на $$$n$$$. Вы можете делать взломы, только если решили обе версии этой задачи.</span></p><p>Перестановка чисел $$$1, 2, \ldots, n$$$ – это последовательность из $$$n$$$ целых чисел, в которой каждое число от $$$1$$$ до $$$n$$$ встречается ровно один раз. Например, $$$[2,3,1,4]$$$ является перестановкой $$$1, 2, 3, 4$$$, но $$$[1,4,2,2]$$$ – не перестановка, поскольку $$$2$$$ встречается здесь дважды.</p><p>Напомним, что количеством инверсий в перестановке $$$a_1, a_2, \ldots, a_n$$$ называется число пар индексов $$$(i, j)$$$ таких, что $$$i &lt; j$$$ и $$$a_i &gt; a_j$$$.</p><p>Пусть $$$p$$$ и $$$q$$$ – две перестановки чисел $$$1, 2, \ldots, n$$$. Найдите количество пар перестановок $$$(p,q)$$$, удовлетворяющих следующим условиям:</p><ul> <li> $$$p$$$ лексикографически меньше $$$q$$$. </li><li> Количество инверсий в $$$p$$$ больше, чем в $$$q$$$. </li></ul><p>Выведите это количество пар по модулю $$$mod$$$. Обратите внимание, что $$$mod$$$ – не обязательно простое число.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке содержатся два целых числа $$$n$$$ и $$$mod$$$ ($$$1\le n\le 500$$$, $$$1\le mod\le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — ответ на задачу по модулю $$$mod$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 403458273 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 17</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Все возможные пары перестановок $$$(p,q)$$$ при $$$n=4$$$:</p><ul> <li> $$$p=[1,3,4,2]$$$, $$$q=[2,1,3,4]$$$, </li><li> $$$p=[1,4,2,3]$$$, $$$q=[2,1,3,4]$$$, </li><li> $$$p=[1,4,3,2]$$$, $$$q=[2,1,3,4]$$$, </li><li> $$$p=[1,4,3,2]$$$, $$$q=[2,1,4,3]$$$, </li><li> $$$p=[1,4,3,2]$$$, $$$q=[2,3,1,4]$$$, </li><li> $$$p=[1,4,3,2]$$$, $$$q=[3,1,2,4]$$$, </li><li> $$$p=[2,3,4,1]$$$, $$$q=[3,1,2,4]$$$, </li><li> $$$p=[2,4,1,3]$$$, $$$q=[3,1,2,4]$$$, </li><li> $$$p=[2,4,3,1]$$$, $$$q=[3,1,2,4]$$$, </li><li> $$$p=[2,4,3,1]$$$, $$$q=[3,1,4,2]$$$, </li><li> $$$p=[2,4,3,1]$$$, $$$q=[3,2,1,4]$$$, </li><li> $$$p=[2,4,3,1]$$$, $$$q=[4,1,2,3]$$$, </li><li> $$$p=[3,2,4,1]$$$, $$$q=[4,1,2,3]$$$, </li><li> $$$p=[3,4,1,2]$$$, $$$q=[4,1,2,3]$$$, </li><li> $$$p=[3,4,2,1]$$$, $$$q=[4,1,2,3]$$$, </li><li> $$$p=[3,4,2,1]$$$, $$$q=[4,1,3,2]$$$, </li><li> $$$p=[3,4,2,1]$$$, $$$q=[4,2,1,3]$$$. </li></ul></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="aff406c2e3103778c50d6460e8d3294a"/> <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="cc177b9c6a05bb6a147cd70438fe0a003547d1ac"/> <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='aff406c2e3103778c50d6460e8d3294a'>&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%2F1542%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='aff406c2e3103778c50d6460e8d3294a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1542">Codeforces Round 729 (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='aff406c2e3103778c50d6460e8d3294a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1542/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Быстрое преобразование Фурье"> бпф </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *2700 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='aff406c2e3103778c50d6460e8d3294a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1034814"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='aff406c2e3103778c50d6460e8d3294a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1034814"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92410" title="Codeforces Round #729 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13966" resourceName="Codeforces Round #729 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/92492" title="Tutorial of Codeforces Round 729 (Div.2)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13973" resourceName="Tutorial of Codeforces Round 729 (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> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1542">Задачи</a></li> <li><a href="/contest/1542/submit">Отослать</a></li> <li><a href="/contest/1542/my">Мои посылки</a></li> <li><a href="/contest/1542/status">Статус</a></li> <li><a href="/contest/1542/hacks">Взломы</a></li> <li><a href="/contest/1542/room/1">Комната</a></li> <li><a href="/contest/1542/standings">Положение</a></li> <li><a href="/contest/1542/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9c45ebbfc66ecec9fd7a27c3825c00403aedf973"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>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><span class="tex-font-style-bf">Это сложная версия задачи. Единственное различие между простой и сложной версиями заключается в ограничениях на $$$n$$$. Вы можете делать взломы, только если решили обе версии этой задачи.</span></p><p>Перестановка чисел $$$1, 2, \ldots, n$$$ – это последовательность из $$$n$$$ целых чисел, в которой каждое число от $$$1$$$ до $$$n$$$ встречается ровно один раз. Например, $$$[2,3,1,4]$$$ является перестановкой $$$1, 2, 3, 4$$$, но $$$[1,4,2,2]$$$ – не перестановка, поскольку $$$2$$$ встречается здесь дважды.</p><p>Напомним, что количеством инверсий в перестановке $$$a_1, a_2, \ldots, a_n$$$ называется число пар индексов $$$(i, j)$$$ таких, что $$$i &lt; j$$$ и $$$a_i &gt; a_j$$$.</p><p>Пусть $$$p$$$ и $$$q$$$ – две перестановки чисел $$$1, 2, \ldots, n$$$. Найдите количество пар перестановок $$$(p,q)$$$, удовлетворяющих следующим условиям:</p><ul> <li> $$$p$$$ лексикографически меньше $$$q$$$. </li><li> Количество инверсий в $$$p$$$ больше, чем в $$$q$$$. </li></ul><p>Выведите это количество пар по модулю $$$mod$$$. Обратите внимание, что $$$mod$$$ – не обязательно простое число.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке содержатся два целых числа $$$n$$$ и $$$mod$$$ ($$$1\le n\le 500$$$, $$$1\le mod\le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — ответ на задачу по модулю $$$mod$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 403458273 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 17</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Все возможные пары перестановок $$$(p,q)$$$ при $$$n=4$$$:</p><ul> <li> $$$p=[1,3,4,2]$$$, $$$q=[2,1,3,4]$$$, </li><li> $$$p=[1,4,2,3]$$$, $$$q=[2,1,3,4]$$$, </li><li> $$$p=[1,4,3,2]$$$, $$$q=[2,1,3,4]$$$, </li><li> $$$p=[1,4,3,2]$$$, $$$q=[2,1,4,3]$$$, </li><li> $$$p=[1,4,3,2]$$$, $$$q=[2,3,1,4]$$$, </li><li> $$$p=[1,4,3,2]$$$, $$$q=[3,1,2,4]$$$, </li><li> $$$p=[2,3,4,1]$$$, $$$q=[3,1,2,4]$$$, </li><li> $$$p=[2,4,1,3]$$$, $$$q=[3,1,2,4]$$$, </li><li> $$$p=[2,4,3,1]$$$, $$$q=[3,1,2,4]$$$, </li><li> $$$p=[2,4,3,1]$$$, $$$q=[3,1,4,2]$$$, </li><li> $$$p=[2,4,3,1]$$$, $$$q=[3,2,1,4]$$$, </li><li> $$$p=[2,4,3,1]$$$, $$$q=[4,1,2,3]$$$, </li><li> $$$p=[3,2,4,1]$$$, $$$q=[4,1,2,3]$$$, </li><li> $$$p=[3,4,1,2]$$$, $$$q=[4,1,2,3]$$$, </li><li> $$$p=[3,4,2,1]$$$, $$$q=[4,1,2,3]$$$, </li><li> $$$p=[3,4,2,1]$$$, $$$q=[4,1,3,2]$$$, </li><li> $$$p=[3,4,2,1]$$$, $$$q=[4,2,1,3]$$$. </li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E2]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c74f0bf67b4b',t:'MTY5NjY2NzM4OS40MzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u043f\u0444", "\u0434\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*2700"]
1543A
1543
A
ru
A. Азартные ставки
<div class="problem-statement"><div class="header"><div class="title">A. Азартные ставки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Добро пожаловать в Рокпорт-Сити! </p><p>Пришло время для вашей первой гонки в игре против Ронни. Чтобы сделать гонку интересной, вы поставили $$$a$$$ долларов, а Ронни — $$$b$$$ долларов. Но, похоже, фанаты разочарованы. Азарт фанатов равен $$$gcd(a,b)$$$, где $$$gcd(x, y)$$$ обозначает <a href="https://ru.wikipedia.org/wiki/Наибольший_общий_делитель">наибольший общий делитель (НОД)</a> чисел $$$x$$$ и $$$y$$$. Чтобы сделать гонку более азартной, вы можете выполнять следующие операции:</p><ol> <li> Увеличить и $$$a$$$, и $$$b$$$ на $$$1$$$. </li><li> Уменьшить и $$$a$$$, и $$$b$$$ на $$$1$$$. Эту операцию разрешено выполнять лишь тогда, когда и $$$a$$$, и $$$b$$$ больше $$$0$$$. </li></ol><p>За один шаг вы можете выполнить любую из этих операций. Вы можете сделать любое (в том числе ноль) число шагов. Определите максимальный азарт, который могут испытать фанаты, и минимальное число шагов, необходимое, чтобы его достичь. </p><p>Обратите внимание, что $$$gcd(x,0)=x$$$ для всех $$$x \ge 0$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1\leq t\leq 5\cdot 10^3$$$) — количество наборов входных данных. </p><p>Первая и единственная строка каждого набора входных данных содержит два целых числа $$$a$$$ и $$$b$$$ ($$$0\leq a, b\leq 10^{18}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите строку, содержащую два целых числа.</p><p>Если фанаты могут испытать бесконечный азарт, выведите <span class="tex-font-style-tt">0 0</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 8 5 1 2 4 4 3 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 1 0 0 0 6 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных вы можете проделать первую операцию $$$1$$$ раз, получив $$$a=9$$$ и $$$b=6$$$. Можно показать, что $$$3$$$ – максимальный возможный азарт.</p><p>Во втором наборе входных данных, независимо от операций, азарт фанатов будет равен $$$1$$$. Поскольку изначальный азарт так же равен $$$1$$$, вам не нужно проделывать никакие операции. </p><p>В третьем наборе входных данных фанаты могут испытать бесконечный азарт, применяя первую операцию бесконечное количество раз. </p><p>В четвертом наборе входных данных вы можете применить вторую операцию $$$3$$$ раза, получив $$$a=0$$$ и $$$b=6$$$. Поскольку $$$gcd(0,6)=6$$$, фанаты испытают азарт, равный $$$6$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="502c735360042af254bd5a2c6de55054"/> <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="c7ad42e2069dd62dfaa44a437fdde403b10c950f"/> <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='502c735360042af254bd5a2c6de55054'>&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%2F1543%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='502c735360042af254bd5a2c6de55054'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1543">Codeforces Round 730 (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='502c735360042af254bd5a2c6de55054'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1543/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='502c735360042af254bd5a2c6de55054'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1038885"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='502c735360042af254bd5a2c6de55054'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1038885"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92543" title="Codeforces Round #730 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13977" resourceName="Codeforces Round #730 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/92582" title="Codeforces Round #730 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13988" resourceName="Codeforces Round #730 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1543">Задачи</a></li> <li><a href="/contest/1543/submit">Отослать</a></li> <li><a href="/contest/1543/my">Мои посылки</a></li> <li><a href="/contest/1543/status">Статус</a></li> <li><a href="/contest/1543/hacks">Взломы</a></li> <li><a href="/contest/1543/room/1">Комната</a></li> <li><a href="/contest/1543/standings">Положение</a></li> <li><a href="/contest/1543/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_48106e373e55bfb879d1afaaa7f8317e0f72a482"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Азартные ставки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Добро пожаловать в Рокпорт-Сити! </p><p>Пришло время для вашей первой гонки в игре против Ронни. Чтобы сделать гонку интересной, вы поставили $$$a$$$ долларов, а Ронни — $$$b$$$ долларов. Но, похоже, фанаты разочарованы. Азарт фанатов равен $$$gcd(a,b)$$$, где $$$gcd(x, y)$$$ обозначает <a href="https://ru.wikipedia.org/wiki/Наибольший_общий_делитель">наибольший общий делитель (НОД)</a> чисел $$$x$$$ и $$$y$$$. Чтобы сделать гонку более азартной, вы можете выполнять следующие операции:</p><ol> <li> Увеличить и $$$a$$$, и $$$b$$$ на $$$1$$$. </li><li> Уменьшить и $$$a$$$, и $$$b$$$ на $$$1$$$. Эту операцию разрешено выполнять лишь тогда, когда и $$$a$$$, и $$$b$$$ больше $$$0$$$. </li></ol><p>За один шаг вы можете выполнить любую из этих операций. Вы можете сделать любое (в том числе ноль) число шагов. Определите максимальный азарт, который могут испытать фанаты, и минимальное число шагов, необходимое, чтобы его достичь. </p><p>Обратите внимание, что $$$gcd(x,0)=x$$$ для всех $$$x \ge 0$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1\leq t\leq 5\cdot 10^3$$$) — количество наборов входных данных. </p><p>Первая и единственная строка каждого набора входных данных содержит два целых числа $$$a$$$ и $$$b$$$ ($$$0\leq a, b\leq 10^{18}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите строку, содержащую два целых числа.</p><p>Если фанаты могут испытать бесконечный азарт, выведите <span class="tex-font-style-tt">0 0</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 8 5 1 2 4 4 3 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 1 0 0 0 6 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных вы можете проделать первую операцию $$$1$$$ раз, получив $$$a=9$$$ и $$$b=6$$$. Можно показать, что $$$3$$$ – максимальный возможный азарт.</p><p>Во втором наборе входных данных, независимо от операций, азарт фанатов будет равен $$$1$$$. Поскольку изначальный азарт так же равен $$$1$$$, вам не нужно проделывать никакие операции. </p><p>В третьем наборе входных данных фанаты могут испытать бесконечный азарт, применяя первую операцию бесконечное количество раз. </p><p>В четвертом наборе входных данных вы можете применить вторую операцию $$$3$$$ раза, получив $$$a=0$$$ и $$$b=6$$$. Поскольку $$$gcd(0,6)=6$$$, фанаты испытают азарт, равный $$$6$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c757bd0c75ab',t:'MTY5NjY2NzM5MC44OTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*900"]
1543B
1543
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>Шоссе 201 — самая оживлённая улица в Рокпорт-Сити. Машины, стоящие в пробках, создают помехи для гонок, особенно когда их много. Гоночная трасса, проходящая через это шоссе, разделена на $$$n$$$ участков. Вам дан массив $$$a$$$, в котором $$$a_i$$$ равно количеству машин, стоящих в пробках на $$$i$$$-м участке. Положим неудобством гоночной трассы значение $$$\sum\limits_{i=1}^{n} \sum\limits_{j=i+1}^{n} \lvert a_i-a_j\rvert$$$, где $$$|x|$$$ — модуль числа $$$x$$$. </p><p>Вам разрешено проделывать следующую операцию любое (в том числе ноль) количество раз: выбрать машину, стоящую в пробке, и переместить ее из ее текущего участка в любой другой участок.</p><p>Найдите минимальное неудобство, которого возможно достичь.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1\leq t\leq 10\,000$$$) — количество наборов входных данных. </p><p>Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$1\leq n\leq 2\cdot 10^5$$$).</p><p>Вторая строка каждого набора содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0\leq a_i\leq 10^9$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите строку, содержащую одно целое число — минимальное неудобство, которого возможно достичь, применяя указанную операцию любое (в том числе ноль) количество раз. </p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 2 3 4 0 1 1 0 10 8 3 6 11 5 2 1 7 10 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 4 21 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных вы можете переместить машину с $$$3$$$-го участка на $$$1$$$-й участок, чтобы получить неудобство, равное $$$0$$$.</p><p>Во втором наборе перемещение любой машины не уменьшит неудобство гоночной трассы. </p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="283d402b0b29fb624197961414bb54e9"/> <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="c7ad42e2069dd62dfaa44a437fdde403b10c950f"/> <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='283d402b0b29fb624197961414bb54e9'>&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%2F1543%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='283d402b0b29fb624197961414bb54e9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1543">Codeforces Round 730 (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='283d402b0b29fb624197961414bb54e9'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1543/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='283d402b0b29fb624197961414bb54e9'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1038886"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='283d402b0b29fb624197961414bb54e9'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1038886"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92543" title="Codeforces Round #730 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13977" resourceName="Codeforces Round #730 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/92582" title="Codeforces Round #730 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13988" resourceName="Codeforces Round #730 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1543">Задачи</a></li> <li><a href="/contest/1543/submit">Отослать</a></li> <li><a href="/contest/1543/my">Мои посылки</a></li> <li><a href="/contest/1543/status">Статус</a></li> <li><a href="/contest/1543/hacks">Взломы</a></li> <li><a href="/contest/1543/room/1">Комната</a></li> <li><a href="/contest/1543/standings">Положение</a></li> <li><a href="/contest/1543/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_446241b64332008a7c95b76efdec0cfbbb221cb2"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Шоссе 201 — самая оживлённая улица в Рокпорт-Сити. Машины, стоящие в пробках, создают помехи для гонок, особенно когда их много. Гоночная трасса, проходящая через это шоссе, разделена на $$$n$$$ участков. Вам дан массив $$$a$$$, в котором $$$a_i$$$ равно количеству машин, стоящих в пробках на $$$i$$$-м участке. Положим неудобством гоночной трассы значение $$$\sum\limits_{i=1}^{n} \sum\limits_{j=i+1}^{n} \lvert a_i-a_j\rvert$$$, где $$$|x|$$$ — модуль числа $$$x$$$. </p><p>Вам разрешено проделывать следующую операцию любое (в том числе ноль) количество раз: выбрать машину, стоящую в пробке, и переместить ее из ее текущего участка в любой другой участок.</p><p>Найдите минимальное неудобство, которого возможно достичь.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1\leq t\leq 10\,000$$$) — количество наборов входных данных. </p><p>Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$1\leq n\leq 2\cdot 10^5$$$).</p><p>Вторая строка каждого набора содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0\leq a_i\leq 10^9$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите строку, содержащую одно целое число — минимальное неудобство, которого возможно достичь, применяя указанную операцию любое (в том числе ноль) количество раз. </p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 2 3 4 0 1 1 0 10 8 3 6 11 5 2 1 7 10 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 4 21 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных вы можете переместить машину с $$$3$$$-го участка на $$$1$$$-й участок, чтобы получить неудобство, равное $$$0$$$.</p><p>Во втором наборе перемещение любой машины не уменьшит неудобство гоночной трассы. </p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c760db799d52',t:'MTY5NjY2NzM5Mi4yNjYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*900"]
1543C
1543
C
ru
C. Машины соперников
<div class="problem-statement"><div class="header"><div class="title">C. Машины соперников</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>После победы над соперником из Чёрного Списка вы получаете шанс вытянуть $$$1$$$ из $$$x$$$ доступных призовых карточек. Изначально $$$x=3$$$ и доступны следующие карточки: <span class="tex-font-style-tt">Взятка</span>, <span class="tex-font-style-tt">Освобождение от конфискации</span> и <span class="tex-font-style-tt">Машина соперника</span>. Изначально вероятность вытянуть их в случайной попытке равна $$$c$$$, $$$m$$$ и $$$p$$$ соответственно. Также присутствует фактор изменчивости $$$v$$$. Вы можете играть в гонки с соперником до тех пор, пока не вытяните карточку <span class="tex-font-style-tt">Машина соперника</span>. Предположим, что вы выигрываете каждую гонку и получаете шанс тянуть призовую карточку. В каждом вытягивании вы достаете одну из $$$x$$$ доступных карточек с соответствующей вероятностью. Пусть вы вытянули карточку и вероятность ее вытягивания до вашей попытки была равна $$$a$$$. Тогда</p><ul> <li> Если это карточка <span class="tex-font-style-tt">Машина соперника</span>, то игра для вас заканчивается и вы больше не можете участвовать в гонках. </li><li> Иначе <ol> <li> Если $$$a\leq v$$$, то вероятность вытянутой карточки становится равной $$$0$$$ и она перестает быть доступной для последующих вытягиваний, уменьшая $$$x$$$ на $$$1$$$. Более того, освободившаяся вероятность $$$a$$$ распределяется равномерно среди оставшихся доступных карточек. </li><li> Если $$$a &gt; v$$$, вероятность вытянутой карточки уменьшается на $$$v$$$, и освободившаяся вероятность распределяется равномерно среди остальных доступных карточек. </li></ol> </li></ul><p>Например, </p><ul> <li> Если $$$(c,m,p)=(0.2,0.1,0.7)$$$ и $$$v=0.1$$$, то после вытягивания карточки <span class="tex-font-style-tt">Взятка</span> новые вероятности будут равны $$$(0.1,0.15,0.75)$$$. </li><li> Если $$$(c,m,p)=(0.1,0.2,0.7)$$$ и $$$v=0.2$$$, то после вытягивания карточки <span class="tex-font-style-tt">Взятка</span> новые вероятности будут равны $$$(\text{Недоступна},0.25,0.75)$$$. </li><li> Если $$$(c,m,p)=(0.2, \text{Недоступна},0.8)$$$ и $$$v=0.1$$$, то после вытягивания карточки <span class="tex-font-style-tt">Взятка</span> новые вероятности будут равны $$$(0.1, \text{Недоступна} ,0.9)$$$. </li><li> Если $$$(c,m,p)=(0.1,\text{Недоступна},0.9)$$$ и $$$v=0.2$$$, то после вытягивания карточки <span class="tex-font-style-tt">Взятка</span> новые вероятности будут равны $$$(\text{Недоступна},\text{Недоступна},1.0)$$$. </li></ul><p>Вам хочется заполучить машину соперника. Для этого вы должны найти математическое ожидание количества гонок, которые нужно пройти, чтобы вытянуть карточку <span class="tex-font-style-tt">Машина соперника</span>. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1\leq t\leq 10$$$) — количество наборов входных данных.</p><p>Первая и единственная строка каждого набора содержит четыре действительных числа $$$c$$$, $$$m$$$, $$$p$$$ и $$$v$$$ ($$$0 &lt; c,m,p &lt; 1$$$, $$$c+m+p=1$$$, $$$0.1\leq v\leq 0.9$$$).</p><p>Гарантируется, что каждое из чисел $$$c$$$, $$$m$$$, $$$p$$$ и $$$v$$$ содержит не более $$$4$$$-х знаков после запятой.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую одно действительное число — математическое ожидание количества гонок, которые нужно пройти, чтобы вытянуть карточку <span class="tex-font-style-tt">Машина соперника</span>. </p><p>Ответ будет считаться верным, если его абсолютная или относительная ошибка не будет превосходить $$$10^{-6}$$$.</p><p>Формально, пусть ваш ответ равен $$$a$$$, а ответ жюри – $$$b$$$. Ваш ответ считается правильным, если $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 0.2 0.2 0.6 0.2 0.4 0.2 0.4 0.8 0.4998 0.4998 0.0004 0.1666 0.3125 0.6561 0.0314 0.2048 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1.532000000000 1.860000000000 5.005050776521 4.260163673896 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Обозначим за <span class="tex-font-style-tt">C</span> вытягивание карточки <span class="tex-font-style-tt">Взятка</span>, за <span class="tex-font-style-tt">M</span> — карточки <span class="tex-font-style-tt">Освобождение от конфискации</span>, за <span class="tex-font-style-tt">P</span> — карточки <span class="tex-font-style-tt">Машина соперника</span>. </p><p>В первом наборе входных данных возможные последовательности вытягиваний представлены ниже: </p><ul> <li> <span class="tex-font-style-tt">P</span> с вероятностью $$$0.6$$$; </li><li> <span class="tex-font-style-tt">CP</span> с вероятностью $$$0.2\cdot 0.7 = 0.14$$$; </li><li> <span class="tex-font-style-tt">CMP</span> с вероятностью $$$0.2\cdot 0.3\cdot 0.9 = 0.054$$$; </li><li> <span class="tex-font-style-tt">CMMP</span> с вероятностью $$$0.2\cdot 0.3\cdot 0.1\cdot 1 = 0.006$$$; </li><li> <span class="tex-font-style-tt">MP</span> с вероятностью $$$0.2\cdot 0.7 = 0.14$$$; </li><li> <span class="tex-font-style-tt">MCP</span> с вероятностью $$$0.2\cdot 0.3\cdot 0.9 = 0.054$$$; </li><li> <span class="tex-font-style-tt">MCCP</span> с вероятностью $$$0.2\cdot 0.3\cdot 0.1\cdot 1 = 0.006$$$; </li></ul> Поэтому математическое ожидание количества гонок равно $$$1\cdot 0.6 + 2\cdot 0.14 + 3\cdot 0.054 + 4\cdot 0.006 + 2\cdot 0.14 + 3\cdot 0.054 + 4\cdot 0.006 = 1.532$$$.<p>Во втором наборе данных возможные последовательности вытягиваний представлены ниже - </p><ul> <li> <span class="tex-font-style-tt">P</span> с вероятностью $$$0.4$$$; </li><li> <span class="tex-font-style-tt">CP</span> с вероятностью $$$0.4\cdot 0.6 = 0.24$$$; </li><li> <span class="tex-font-style-tt">CMP</span> с вероятностью $$$0.4\cdot 0.4\cdot 1 = 0.16$$$; </li><li> <span class="tex-font-style-tt">MP</span> с вероятностью $$$0.2\cdot 0.5 = 0.1$$$; </li><li> <span class="tex-font-style-tt">MCP</span> с вероятностью $$$0.2\cdot 0.5\cdot 1 = 0.1$$$. </li></ul><p>Поэтому математическое ожидание количества гонок равно $$$1\cdot 0.4 + 2\cdot 0.24 + 3\cdot 0.16 + 2\cdot 0.1 + 3\cdot 0.1 = 1.86$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="e613bb8f6f8ee571eb321c611ac94c69"/> <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="c7ad42e2069dd62dfaa44a437fdde403b10c950f"/> <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='e613bb8f6f8ee571eb321c611ac94c69'>&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%2F1543%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='e613bb8f6f8ee571eb321c611ac94c69'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1543">Codeforces Round 730 (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='e613bb8f6f8ee571eb321c611ac94c69'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1543/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='e613bb8f6f8ee571eb321c611ac94c69'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1038887"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e613bb8f6f8ee571eb321c611ac94c69'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1038887"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92543" title="Codeforces Round #730 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13977" resourceName="Codeforces Round #730 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/92582" title="Codeforces Round #730 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13988" resourceName="Codeforces Round #730 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1543">Задачи</a></li> <li><a href="/contest/1543/submit">Отослать</a></li> <li><a href="/contest/1543/my">Мои посылки</a></li> <li><a href="/contest/1543/status">Статус</a></li> <li><a href="/contest/1543/hacks">Взломы</a></li> <li><a href="/contest/1543/room/1">Комната</a></li> <li><a href="/contest/1543/standings">Положение</a></li> <li><a href="/contest/1543/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0e51f813b90d5a610f6494365ecfe389a2cc936e"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>После победы над соперником из Чёрного Списка вы получаете шанс вытянуть $$$1$$$ из $$$x$$$ доступных призовых карточек. Изначально $$$x=3$$$ и доступны следующие карточки: <span class="tex-font-style-tt">Взятка</span>, <span class="tex-font-style-tt">Освобождение от конфискации</span> и <span class="tex-font-style-tt">Машина соперника</span>. Изначально вероятность вытянуть их в случайной попытке равна $$$c$$$, $$$m$$$ и $$$p$$$ соответственно. Также присутствует фактор изменчивости $$$v$$$. Вы можете играть в гонки с соперником до тех пор, пока не вытяните карточку <span class="tex-font-style-tt">Машина соперника</span>. Предположим, что вы выигрываете каждую гонку и получаете шанс тянуть призовую карточку. В каждом вытягивании вы достаете одну из $$$x$$$ доступных карточек с соответствующей вероятностью. Пусть вы вытянули карточку и вероятность ее вытягивания до вашей попытки была равна $$$a$$$. Тогда</p><ul> <li> Если это карточка <span class="tex-font-style-tt">Машина соперника</span>, то игра для вас заканчивается и вы больше не можете участвовать в гонках. </li><li> Иначе <ol> <li> Если $$$a\leq v$$$, то вероятность вытянутой карточки становится равной $$$0$$$ и она перестает быть доступной для последующих вытягиваний, уменьшая $$$x$$$ на $$$1$$$. Более того, освободившаяся вероятность $$$a$$$ распределяется равномерно среди оставшихся доступных карточек. </li><li> Если $$$a &gt; v$$$, вероятность вытянутой карточки уменьшается на $$$v$$$, и освободившаяся вероятность распределяется равномерно среди остальных доступных карточек. </li></ol> </li></ul><p>Например, </p><ul> <li> Если $$$(c,m,p)=(0.2,0.1,0.7)$$$ и $$$v=0.1$$$, то после вытягивания карточки <span class="tex-font-style-tt">Взятка</span> новые вероятности будут равны $$$(0.1,0.15,0.75)$$$. </li><li> Если $$$(c,m,p)=(0.1,0.2,0.7)$$$ и $$$v=0.2$$$, то после вытягивания карточки <span class="tex-font-style-tt">Взятка</span> новые вероятности будут равны $$$(\text{Недоступна},0.25,0.75)$$$. </li><li> Если $$$(c,m,p)=(0.2, \text{Недоступна},0.8)$$$ и $$$v=0.1$$$, то после вытягивания карточки <span class="tex-font-style-tt">Взятка</span> новые вероятности будут равны $$$(0.1, \text{Недоступна} ,0.9)$$$. </li><li> Если $$$(c,m,p)=(0.1,\text{Недоступна},0.9)$$$ и $$$v=0.2$$$, то после вытягивания карточки <span class="tex-font-style-tt">Взятка</span> новые вероятности будут равны $$$(\text{Недоступна},\text{Недоступна},1.0)$$$. </li></ul><p>Вам хочется заполучить машину соперника. Для этого вы должны найти математическое ожидание количества гонок, которые нужно пройти, чтобы вытянуть карточку <span class="tex-font-style-tt">Машина соперника</span>. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1\leq t\leq 10$$$) — количество наборов входных данных.</p><p>Первая и единственная строка каждого набора содержит четыре действительных числа $$$c$$$, $$$m$$$, $$$p$$$ и $$$v$$$ ($$$0 &lt; c,m,p &lt; 1$$$, $$$c+m+p=1$$$, $$$0.1\leq v\leq 0.9$$$).</p><p>Гарантируется, что каждое из чисел $$$c$$$, $$$m$$$, $$$p$$$ и $$$v$$$ содержит не более $$$4$$$-х знаков после запятой.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую одно действительное число — математическое ожидание количества гонок, которые нужно пройти, чтобы вытянуть карточку <span class="tex-font-style-tt">Машина соперника</span>. </p><p>Ответ будет считаться верным, если его абсолютная или относительная ошибка не будет превосходить $$$10^{-6}$$$.</p><p>Формально, пусть ваш ответ равен $$$a$$$, а ответ жюри – $$$b$$$. Ваш ответ считается правильным, если $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 0.2 0.2 0.6 0.2 0.4 0.2 0.4 0.8 0.4998 0.4998 0.0004 0.1666 0.3125 0.6561 0.0314 0.2048 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1.532000000000 1.860000000000 5.005050776521 4.260163673896 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Обозначим за <span class="tex-font-style-tt">C</span> вытягивание карточки <span class="tex-font-style-tt">Взятка</span>, за <span class="tex-font-style-tt">M</span> — карточки <span class="tex-font-style-tt">Освобождение от конфискации</span>, за <span class="tex-font-style-tt">P</span> — карточки <span class="tex-font-style-tt">Машина соперника</span>. </p><p>В первом наборе входных данных возможные последовательности вытягиваний представлены ниже: </p><ul> <li> <span class="tex-font-style-tt">P</span> с вероятностью $$$0.6$$$; </li><li> <span class="tex-font-style-tt">CP</span> с вероятностью $$$0.2\cdot 0.7 = 0.14$$$; </li><li> <span class="tex-font-style-tt">CMP</span> с вероятностью $$$0.2\cdot 0.3\cdot 0.9 = 0.054$$$; </li><li> <span class="tex-font-style-tt">CMMP</span> с вероятностью $$$0.2\cdot 0.3\cdot 0.1\cdot 1 = 0.006$$$; </li><li> <span class="tex-font-style-tt">MP</span> с вероятностью $$$0.2\cdot 0.7 = 0.14$$$; </li><li> <span class="tex-font-style-tt">MCP</span> с вероятностью $$$0.2\cdot 0.3\cdot 0.9 = 0.054$$$; </li><li> <span class="tex-font-style-tt">MCCP</span> с вероятностью $$$0.2\cdot 0.3\cdot 0.1\cdot 1 = 0.006$$$; </li></ul> Поэтому математическое ожидание количества гонок равно $$$1\cdot 0.6 + 2\cdot 0.14 + 3\cdot 0.054 + 4\cdot 0.006 + 2\cdot 0.14 + 3\cdot 0.054 + 4\cdot 0.006 = 1.532$$$.<p>Во втором наборе данных возможные последовательности вытягиваний представлены ниже - </p><ul> <li> <span class="tex-font-style-tt">P</span> с вероятностью $$$0.4$$$; </li><li> <span class="tex-font-style-tt">CP</span> с вероятностью $$$0.4\cdot 0.6 = 0.24$$$; </li><li> <span class="tex-font-style-tt">CMP</span> с вероятностью $$$0.4\cdot 0.4\cdot 1 = 0.16$$$; </li><li> <span class="tex-font-style-tt">MP</span> с вероятностью $$$0.2\cdot 0.5 = 0.1$$$; </li><li> <span class="tex-font-style-tt">MCP</span> с вероятностью $$$0.2\cdot 0.5\cdot 1 = 0.1$$$. </li></ul><p>Поэтому математическое ожидание количества гонок равно $$$1\cdot 0.4 + 2\cdot 0.24 + 3\cdot 0.16 + 2\cdot 0.1 + 3\cdot 0.1 = 1.86$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c769489a7b4f',t:'MTY5NjY2NzM5My42MjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\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", "\u0412\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0438, \u043c\u0430\u0442. \u043e\u0436\u0438\u0434\u0430\u043d\u0438\u044f, \u0441\u043b\u0443\u0447\u0430\u0439\u043d\u044b\u0435 \u0432\u0435\u043b\u0438\u0447\u0438\u043d\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*1900"]
1543D1
1543
D1
ru
D1. ПРС и криминальный список (простая версия)
<div class="problem-statement"><div class="header"><div class="title">D1. ПРС и криминальный список (простая версия)</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-bf">Это простая версия задачи. Единственное различие между простой и сложной версиями заключается в том, что в этой версии $$$k=2$$$. Вы можете делать взломы, только если решили обе версии этой задачи.</span></p><p><span class="tex-font-style-it">Это интерактивная задача.</span></p><p>Для каждого десятичного числа есть соответствующая ему $$$k$$$-ичная запись. Цифры числа, записанного в $$$k$$$-ичной системе счисления, будем называть $$$k$$$-цифрами. Определим $$$k$$$-ичный XOR двух $$$k$$$-цифр $$$a$$$ и $$$b$$$ как $$$(a + b)\bmod k$$$. </p><p>$$$k$$$-ичный XOR двух $$$k$$$-ичных чисел равен числу, полученному попарным $$$k$$$-ичным XOR соответствующих $$$k$$$-цифр. $$$k$$$-ичный XOR двух десятичных чисел $$$a$$$ и $$$b$$$ обозначается $$$a\oplus_{k} b$$$ и равен десятичному представлению $$$k$$$-ичного XOR $$$a$$$ и $$$b$$$, записанных в $$$k$$$-ичной системе счисления. Все числа, встречающиеся далее в условии, записаны в десятичной системе счисления, если не указано иное. В случае $$$k = 2$$$, что всегда верно для этой версии задачи, $$$k$$$-ичный XOR — это то же самое, что <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">побитовое исключающее ИЛИ</a>.</p><p>Вы взломали базу преступлений Полиции Рокпорт-Сити (ПРС), так же известную как Криминальный Список. Но, чтобы получить к ней доступ, вам нужен пароль. Вы его не знаете, но вполне уверены, что его значение лежит между $$$0$$$ и $$$n-1$$$ включительно. Вы решили угадать его. Вы можете сделать не более чем $$$n$$$ попыток, далее система заблокируется. Система адаптивна – каждый раз, когда вы делаете неверную попытку, она меняет пароль. А именно, если до попытки пароль был равен $$$x$$$ и вы попытались ввести другое число $$$y$$$, то система поменяет пароль на число $$$z$$$ такое, что $$$x\oplus_{k} z=y$$$. Угадайте пароль и взломайте систему. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1\leq t\leq 10\,000$$$) — количество наборов входных данных. Далее следует описание $$$t$$$ наборов входных данных. </p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ ($$$1\leq n\leq 2\cdot 10^5$$$) и $$$k$$$ ($$$k=2$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2\cdot 10^5$$$.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Для каждого набора входных данных считайте два целых числа $$$n$$$ и $$$k$$$. Вам разрешено сделать не более $$$n$$$ попыток угадать пароль.</p><p>Для каждой попытки выведите одно целое число $$$y$$$ ($$$0\leq y\leq 2\cdot 10^7$$$). Пусть текущий пароль равен $$$x$$$. Считайте одно целое число $$$r$$$.</p><p>Если $$$x=y$$$, вы считаете $$$r=1$$$, и этот набор входных данных считается решенным. Далее вы должны продолжить решать оставшиеся наборы. </p><p>Иначе вы считаете $$$r=0$$$, и система поменяет пароль на число $$$z$$$ такое, что $$$x\oplus_{k} z=y$$$.</p><p>После каждой попытки не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul> <li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++; </li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java; </li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal; </li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python; </li><li> смотрите документацию для других языков. </li></ul><p>Если вы сделаете некорректную попытку или превысите лимит в $$$n$$$ попыток, вы считаете $$$r=-1$$$ вместо ответа и получите вердикт <span class="tex-font-style-tt">Неправильный ответ</span>. В таком случае ваша программа должна немедленно завершается, чтобы избежать неопределенных вердиктов.</p><p>Обратите внимание, что система <span class="tex-font-style-bf">адаптивна</span>. Это значит, что изначальный пароль не зафиксирован в начале и может зависеть от ваших запросов. Гарантируется, что в любой момент времени существует хотя бы один начальный пароль, для которого согласуются все ответы на запросы. </p><p><span class="tex-font-style-bf">Взломы:</span></p><p>Для взломов используйте следующий формат:</p><p>Первая строка должна содержать одно целое число $$$t$$$ ($$$1\leq t\leq 10\,000$$$) — количество наборов входных данных. </p><p>Первая и единственная строка каждого набора должна содержать два целых числа $$$n$$$ ($$$1\leq n\leq 2\cdot 10^5$$$) и $$$k$$$ ($$$k=2$$$), равные соответственно количеству возможных попыток и основанию системы счисления. Оптимальный начальный пароль будет автоматически подобран системой. </p><p>Сумма $$$n$$$ по всем наборам входных данных не должна превышать $$$2\cdot 10^5$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 5 2 0 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 4 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В этом наборе входных данных загаданный пароль равен $$$2$$$. </p><p>Первая попытка равна $$$3$$$. Это не равно текущему паролю. Поэтому система возвращает ответ $$$0$$$ и меняет пароль на $$$1$$$, поскольку $$$2\oplus_2 1=3$$$.</p><p>Вторая попытка равна $$$4$$$. Это не равно текущему паролю. Поэтому система возвращает ответ $$$0$$$ и меняет пароль на $$$5$$$, поскольку $$$1\oplus_2 5=4$$$.</p><p>Третья попытка равна $$$5$$$. Это равно текущему паролю. Поэтому система возвращает ответ $$$1$$$ и работа сделана. </p><p>Заметьте, что начальный пароль был взят таким для наглядности объяснения. В действительности система может повести себя иначе, поскольку она адаптивна. </p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="767c1d30d51ffd134b1b2561ce4977ec"/> <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="c7ad42e2069dd62dfaa44a437fdde403b10c950f"/> <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='767c1d30d51ffd134b1b2561ce4977ec'>&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%2F1543%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='767c1d30d51ffd134b1b2561ce4977ec'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1543">Codeforces Round 730 (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='767c1d30d51ffd134b1b2561ce4977ec'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1543/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *1700 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='767c1d30d51ffd134b1b2561ce4977ec'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1038888"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='767c1d30d51ffd134b1b2561ce4977ec'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1038888"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92543" title="Codeforces Round #730 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13977" resourceName="Codeforces Round #730 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/92582" title="Codeforces Round #730 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13988" resourceName="Codeforces Round #730 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1543">Задачи</a></li> <li><a href="/contest/1543/submit">Отослать</a></li> <li><a href="/contest/1543/my">Мои посылки</a></li> <li><a href="/contest/1543/status">Статус</a></li> <li><a href="/contest/1543/hacks">Взломы</a></li> <li><a href="/contest/1543/room/1">Комната</a></li> <li><a href="/contest/1543/standings">Положение</a></li> <li><a href="/contest/1543/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_4678a478d5e65309c3645d079e1c6a60b544cb77"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это простая версия задачи. Единственное различие между простой и сложной версиями заключается в том, что в этой версии $$$k=2$$$. Вы можете делать взломы, только если решили обе версии этой задачи.</span></p><p><span class="tex-font-style-it">Это интерактивная задача.</span></p><p>Для каждого десятичного числа есть соответствующая ему $$$k$$$-ичная запись. Цифры числа, записанного в $$$k$$$-ичной системе счисления, будем называть $$$k$$$-цифрами. Определим $$$k$$$-ичный XOR двух $$$k$$$-цифр $$$a$$$ и $$$b$$$ как $$$(a + b)\bmod k$$$. </p><p>$$$k$$$-ичный XOR двух $$$k$$$-ичных чисел равен числу, полученному попарным $$$k$$$-ичным XOR соответствующих $$$k$$$-цифр. $$$k$$$-ичный XOR двух десятичных чисел $$$a$$$ и $$$b$$$ обозначается $$$a\oplus_{k} b$$$ и равен десятичному представлению $$$k$$$-ичного XOR $$$a$$$ и $$$b$$$, записанных в $$$k$$$-ичной системе счисления. Все числа, встречающиеся далее в условии, записаны в десятичной системе счисления, если не указано иное. В случае $$$k = 2$$$, что всегда верно для этой версии задачи, $$$k$$$-ичный XOR — это то же самое, что <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">побитовое исключающее ИЛИ</a>.</p><p>Вы взломали базу преступлений Полиции Рокпорт-Сити (ПРС), так же известную как Криминальный Список. Но, чтобы получить к ней доступ, вам нужен пароль. Вы его не знаете, но вполне уверены, что его значение лежит между $$$0$$$ и $$$n-1$$$ включительно. Вы решили угадать его. Вы можете сделать не более чем $$$n$$$ попыток, далее система заблокируется. Система адаптивна – каждый раз, когда вы делаете неверную попытку, она меняет пароль. А именно, если до попытки пароль был равен $$$x$$$ и вы попытались ввести другое число $$$y$$$, то система поменяет пароль на число $$$z$$$ такое, что $$$x\oplus_{k} z=y$$$. Угадайте пароль и взломайте систему. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1\leq t\leq 10\,000$$$) — количество наборов входных данных. Далее следует описание $$$t$$$ наборов входных данных. </p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ ($$$1\leq n\leq 2\cdot 10^5$$$) и $$$k$$$ ($$$k=2$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2\cdot 10^5$$$.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Для каждого набора входных данных считайте два целых числа $$$n$$$ и $$$k$$$. Вам разрешено сделать не более $$$n$$$ попыток угадать пароль.</p><p>Для каждой попытки выведите одно целое число $$$y$$$ ($$$0\leq y\leq 2\cdot 10^7$$$). Пусть текущий пароль равен $$$x$$$. Считайте одно целое число $$$r$$$.</p><p>Если $$$x=y$$$, вы считаете $$$r=1$$$, и этот набор входных данных считается решенным. Далее вы должны продолжить решать оставшиеся наборы. </p><p>Иначе вы считаете $$$r=0$$$, и система поменяет пароль на число $$$z$$$ такое, что $$$x\oplus_{k} z=y$$$.</p><p>После каждой попытки не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul> <li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++; </li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java; </li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal; </li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python; </li><li> смотрите документацию для других языков. </li></ul><p>Если вы сделаете некорректную попытку или превысите лимит в $$$n$$$ попыток, вы считаете $$$r=-1$$$ вместо ответа и получите вердикт <span class="tex-font-style-tt">Неправильный ответ</span>. В таком случае ваша программа должна немедленно завершается, чтобы избежать неопределенных вердиктов.</p><p>Обратите внимание, что система <span class="tex-font-style-bf">адаптивна</span>. Это значит, что изначальный пароль не зафиксирован в начале и может зависеть от ваших запросов. Гарантируется, что в любой момент времени существует хотя бы один начальный пароль, для которого согласуются все ответы на запросы. </p><p><span class="tex-font-style-bf">Взломы:</span></p><p>Для взломов используйте следующий формат:</p><p>Первая строка должна содержать одно целое число $$$t$$$ ($$$1\leq t\leq 10\,000$$$) — количество наборов входных данных. </p><p>Первая и единственная строка каждого набора должна содержать два целых числа $$$n$$$ ($$$1\leq n\leq 2\cdot 10^5$$$) и $$$k$$$ ($$$k=2$$$), равные соответственно количеству возможных попыток и основанию системы счисления. Оптимальный начальный пароль будет автоматически подобран системой. </p><p>Сумма $$$n$$$ по всем наборам входных данных не должна превышать $$$2\cdot 10^5$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 5 2 0 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 4 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В этом наборе входных данных загаданный пароль равен $$$2$$$. </p><p>Первая попытка равна $$$3$$$. Это не равно текущему паролю. Поэтому система возвращает ответ $$$0$$$ и меняет пароль на $$$1$$$, поскольку $$$2\oplus_2 1=3$$$.</p><p>Вторая попытка равна $$$4$$$. Это не равно текущему паролю. Поэтому система возвращает ответ $$$0$$$ и меняет пароль на $$$5$$$, поскольку $$$1\oplus_2 5=4$$$.</p><p>Третья попытка равна $$$5$$$. Это равно текущему паролю. Поэтому система возвращает ответ $$$1$$$ и работа сделана. </p><p>Заметьте, что начальный пароль был взят таким для наглядности объяснения. В действительности система может повести себя иначе, поскольку она адаптивна. </p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D1]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c771cfbb005c',t:'MTY5NjY2NzM5NS4yMzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1700"]
1543D2
1543
D2
ru
D2. ПРС и криминальный список (сложная версия)
<div class="problem-statement"><div class="header"><div class="title">D2. ПРС и криминальный список (сложная версия)</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-bf">Это сложная версия задачи. Единственное различие между простой и сложной версиями заключается в том, что здесь $$$2\leq k\leq 100$$$. Вы можете делать взломы, только если решили обе версии этой задачи.</span></p><p><span class="tex-font-style-bf">Это интерактивная задача!</span></p><p>Для каждого десятичного числа есть эквивалентное ему $$$k$$$-ичное. Цифры числа, записанного в $$$k$$$-ичной системе счисления, будем называть $$$k$$$-цифрами. Определим $$$k$$$-ичный XOR двух $$$k$$$-цифр $$$a$$$ и $$$b$$$ как $$$(a + b)\bmod k$$$. </p><p>$$$k$$$-ичный XOR двух $$$k$$$-ичных чисел равен новому числу, полученному из первых двух попарным $$$k$$$-ичным XOR соответствующих $$$k$$$-цифр. $$$k$$$-ичный XOR двух десятичных чисел $$$a$$$ и $$$b$$$ обозначается $$$a\oplus_{k} b$$$ и равен десятичному представлению $$$k$$$-ичного XOR $$$a$$$ и $$$b$$$, записанных в $$$k$$$-ичной системе счисления. Все числа, встречающиеся далее в условии, записаны в десятичной системе счисления, если не указано иное.</p><p>Вы взломали базу преступлений Полиции Рокпорт-Сити (ПРС), так же известную как Криминальный Список. Но, чтобы получить к ней доступ, вам нужен пароль. Вы его не знаете, но вполне уверены, что его значение лежит между $$$0$$$ и $$$n-1$$$ включительно. Вы решили угадать его. Вы можете сделать не более чем $$$n$$$ попыток, далее система заблокируется. Система адаптивна – каждый раз, когда вы делаете неверную попытку, она меняет пароль. А именно, если до попытки пароль был равен $$$x$$$ и вы попытались ввести другое число $$$y$$$, то система поменяет пароль на число $$$z$$$ такое, что $$$x\oplus_{k} z=y$$$. Угадайте пароль и взломайте систему. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1\leq t\leq 10\,000$$$) — количество наборов входных данных. Далее следует описание $$$t$$$ наборов входных данных. </p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ ($$$1\leq n\leq 2\cdot 10^5$$$) и $$$k$$$ $$$(2\leq k\leq 100)$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2\cdot 10^5$$$.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Для каждого набора входных данных считайте два целых числа $$$n$$$ и $$$k$$$. Вам разрешено сделать не более $$$n$$$ попыток угадать пароль.</p><p>Для каждой попытки выведите одно целое число $$$y$$$ ($$$0\leq y\leq 2\cdot 10^7$$$). Пусть текущий пароль равен $$$x$$$. Считайте одно целое число $$$r$$$.</p><p>Если $$$x=y$$$, вы считаете $$$r=1$$$, и этот набор входных данных считается решенным. Далее вы должны продолжить решать оставшиеся наборы. </p><p>Иначе вы считаете $$$r=0$$$, и система поменяет пароль на число $$$z$$$ такое, что $$$x\oplus_{k} z=y$$$.</p><p>После каждой попытки не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul> <li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++; </li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java; </li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal; </li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python; </li><li> смотрите документацию для других языков. </li></ul><p>Если вы сделаете некорректную попытку или превысите лимит в $$$n$$$ попыток, вы считаете $$$r=-1$$$ вместо ответа и получите вердикт <span class="tex-font-style-tt">Неправильный ответ</span>. В таком случае ваша программа должна немедленно завершается, чтобы избежать неопределенных вердиктов.</p><p>Обратите внимание, что система <span class="tex-font-style-bf">адаптивна</span>. Это значит, что изначальный пароль не зафиксирован в начале и может зависеть от ваших запросов. Гарантируется, что в любой момент времени существует хотя бы один начальный пароль, для которого согласуются все ответы на запросы. </p><p><span class="tex-font-style-bf">Взломы:</span></p><p>Для взломов используйте следующий формат:</p><p>Первая строка должна содержать одно целое число $$$t$$$ ($$$1\leq t\leq 10\,000$$$) — количество наборов входных данных. </p><p>Первая и единственная строка каждого набора должна содержать два целых числа $$$n$$$ ($$$1\leq n\leq 2\cdot 10^5$$$) и $$$k$$$ ($$$2\leq k\leq 100$$$), равные соответственно количеству возможных попыток и основанию системы счисления. Оптимальный начальный пароль будет автоматически подобран системой. </p><p>Сумма $$$n$$$ по всем наборам входных данных не должна превышать $$$2\cdot 10^5$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 5 2 0 0 1 5 3 0 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 4 5 1 4 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p><span class="tex-font-style-bf">Набор 1:</span></p><p>В этом наборе входных данных загаданный пароль равен $$$2$$$. </p><p>Первая попытка равна $$$3$$$. Это не равно текущему паролю. Поэтому система возвращает ответ $$$0$$$ и меняет пароль на $$$1$$$, поскольку $$$2\oplus_2 1=3$$$.</p><p>Вторая попытка равна $$$4$$$. Это не равно текущему паролю. Поэтому система возвращает ответ $$$0$$$ и меняет пароль на $$$5$$$, поскольку $$$1\oplus_2 5=4$$$.</p><p>Третья попытка равна $$$5$$$. Это равно текущему паролю. Поэтому система возвращает ответ $$$1$$$ и работа сделана. </p><p><span class="tex-font-style-bf">Набор 2:</span></p><p>В этом наборе входных данных загаданный пароль равен $$$3$$$.</p><p>Первая попытка равна $$$1$$$. Это не равно текущему паролю. Поэтому система возвращает $$$0$$$ и меняет пароль на $$$7$$$, поскольку $$$3\oplus_3 7=1$$$. $$$[3=(10)_3$$$, $$$7=(21)_3$$$, $$$1=(01)_3$$$ и $$$(10)_3\oplus_3 (21)_3 = (01)_3]$$$.</p><p>Вторая попытка равна $$$4$$$. Это не равно текущему паролю. Поэтому система возвращает $$$0$$$ и меняет пароль на $$$6$$$, поскольку $$$7\oplus_3 6=4$$$. $$$[7=(21)_3$$$, $$$6=(20)_3$$$, $$$4=(11)_3$$$ and $$$(21)_3\oplus_3 (20)_3 = (11)_3]$$$.</p><p>Третья попытка равна $$$6$$$. Это равно текущему паролю. Поэтому система возвращает ответ $$$1$$$ и работа сделана. </p><p>Заметьте, что начальные пароли были взяты такими для наглядности объяснения. В действительности система может повести себя иначе, поскольку она адаптивна. </p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="aaa005059e69755651ec1bf50c81f7e9"/> <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="c7ad42e2069dd62dfaa44a437fdde403b10c950f"/> <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='aaa005059e69755651ec1bf50c81f7e9'>&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%2F1543%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='aaa005059e69755651ec1bf50c81f7e9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1543">Codeforces Round 730 (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='aaa005059e69755651ec1bf50c81f7e9'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1543/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача"> интерактив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *2200 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='aaa005059e69755651ec1bf50c81f7e9'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1038889"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='aaa005059e69755651ec1bf50c81f7e9'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1038889"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92543" title="Codeforces Round #730 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13977" resourceName="Codeforces Round #730 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/92582" title="Codeforces Round #730 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13988" resourceName="Codeforces Round #730 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1543">Задачи</a></li> <li><a href="/contest/1543/submit">Отослать</a></li> <li><a href="/contest/1543/my">Мои посылки</a></li> <li><a href="/contest/1543/status">Статус</a></li> <li><a href="/contest/1543/hacks">Взломы</a></li> <li><a href="/contest/1543/room/1">Комната</a></li> <li><a href="/contest/1543/standings">Положение</a></li> <li><a href="/contest/1543/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2fe211e0b13c63284df0068b3f7f8157043dd92b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это сложная версия задачи. Единственное различие между простой и сложной версиями заключается в том, что здесь $$$2\leq k\leq 100$$$. Вы можете делать взломы, только если решили обе версии этой задачи.</span></p><p><span class="tex-font-style-bf">Это интерактивная задача!</span></p><p>Для каждого десятичного числа есть эквивалентное ему $$$k$$$-ичное. Цифры числа, записанного в $$$k$$$-ичной системе счисления, будем называть $$$k$$$-цифрами. Определим $$$k$$$-ичный XOR двух $$$k$$$-цифр $$$a$$$ и $$$b$$$ как $$$(a + b)\bmod k$$$. </p><p>$$$k$$$-ичный XOR двух $$$k$$$-ичных чисел равен новому числу, полученному из первых двух попарным $$$k$$$-ичным XOR соответствующих $$$k$$$-цифр. $$$k$$$-ичный XOR двух десятичных чисел $$$a$$$ и $$$b$$$ обозначается $$$a\oplus_{k} b$$$ и равен десятичному представлению $$$k$$$-ичного XOR $$$a$$$ и $$$b$$$, записанных в $$$k$$$-ичной системе счисления. Все числа, встречающиеся далее в условии, записаны в десятичной системе счисления, если не указано иное.</p><p>Вы взломали базу преступлений Полиции Рокпорт-Сити (ПРС), так же известную как Криминальный Список. Но, чтобы получить к ней доступ, вам нужен пароль. Вы его не знаете, но вполне уверены, что его значение лежит между $$$0$$$ и $$$n-1$$$ включительно. Вы решили угадать его. Вы можете сделать не более чем $$$n$$$ попыток, далее система заблокируется. Система адаптивна – каждый раз, когда вы делаете неверную попытку, она меняет пароль. А именно, если до попытки пароль был равен $$$x$$$ и вы попытались ввести другое число $$$y$$$, то система поменяет пароль на число $$$z$$$ такое, что $$$x\oplus_{k} z=y$$$. Угадайте пароль и взломайте систему. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1\leq t\leq 10\,000$$$) — количество наборов входных данных. Далее следует описание $$$t$$$ наборов входных данных. </p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ ($$$1\leq n\leq 2\cdot 10^5$$$) и $$$k$$$ $$$(2\leq k\leq 100)$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2\cdot 10^5$$$.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Для каждого набора входных данных считайте два целых числа $$$n$$$ и $$$k$$$. Вам разрешено сделать не более $$$n$$$ попыток угадать пароль.</p><p>Для каждой попытки выведите одно целое число $$$y$$$ ($$$0\leq y\leq 2\cdot 10^7$$$). Пусть текущий пароль равен $$$x$$$. Считайте одно целое число $$$r$$$.</p><p>Если $$$x=y$$$, вы считаете $$$r=1$$$, и этот набор входных данных считается решенным. Далее вы должны продолжить решать оставшиеся наборы. </p><p>Иначе вы считаете $$$r=0$$$, и система поменяет пароль на число $$$z$$$ такое, что $$$x\oplus_{k} z=y$$$.</p><p>После каждой попытки не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul> <li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++; </li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java; </li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal; </li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python; </li><li> смотрите документацию для других языков. </li></ul><p>Если вы сделаете некорректную попытку или превысите лимит в $$$n$$$ попыток, вы считаете $$$r=-1$$$ вместо ответа и получите вердикт <span class="tex-font-style-tt">Неправильный ответ</span>. В таком случае ваша программа должна немедленно завершается, чтобы избежать неопределенных вердиктов.</p><p>Обратите внимание, что система <span class="tex-font-style-bf">адаптивна</span>. Это значит, что изначальный пароль не зафиксирован в начале и может зависеть от ваших запросов. Гарантируется, что в любой момент времени существует хотя бы один начальный пароль, для которого согласуются все ответы на запросы. </p><p><span class="tex-font-style-bf">Взломы:</span></p><p>Для взломов используйте следующий формат:</p><p>Первая строка должна содержать одно целое число $$$t$$$ ($$$1\leq t\leq 10\,000$$$) — количество наборов входных данных. </p><p>Первая и единственная строка каждого набора должна содержать два целых числа $$$n$$$ ($$$1\leq n\leq 2\cdot 10^5$$$) и $$$k$$$ ($$$2\leq k\leq 100$$$), равные соответственно количеству возможных попыток и основанию системы счисления. Оптимальный начальный пароль будет автоматически подобран системой. </p><p>Сумма $$$n$$$ по всем наборам входных данных не должна превышать $$$2\cdot 10^5$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 5 2 0 0 1 5 3 0 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 4 5 1 4 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p><span class="tex-font-style-bf">Набор 1:</span></p><p>В этом наборе входных данных загаданный пароль равен $$$2$$$. </p><p>Первая попытка равна $$$3$$$. Это не равно текущему паролю. Поэтому система возвращает ответ $$$0$$$ и меняет пароль на $$$1$$$, поскольку $$$2\oplus_2 1=3$$$.</p><p>Вторая попытка равна $$$4$$$. Это не равно текущему паролю. Поэтому система возвращает ответ $$$0$$$ и меняет пароль на $$$5$$$, поскольку $$$1\oplus_2 5=4$$$.</p><p>Третья попытка равна $$$5$$$. Это равно текущему паролю. Поэтому система возвращает ответ $$$1$$$ и работа сделана. </p><p><span class="tex-font-style-bf">Набор 2:</span></p><p>В этом наборе входных данных загаданный пароль равен $$$3$$$.</p><p>Первая попытка равна $$$1$$$. Это не равно текущему паролю. Поэтому система возвращает $$$0$$$ и меняет пароль на $$$7$$$, поскольку $$$3\oplus_3 7=1$$$. $$$[3=(10)_3$$$, $$$7=(21)_3$$$, $$$1=(01)_3$$$ и $$$(10)_3\oplus_3 (21)_3 = (01)_3]$$$.</p><p>Вторая попытка равна $$$4$$$. Это не равно текущему паролю. Поэтому система возвращает $$$0$$$ и меняет пароль на $$$6$$$, поскольку $$$7\oplus_3 6=4$$$. $$$[7=(21)_3$$$, $$$6=(20)_3$$$, $$$4=(11)_3$$$ and $$$(21)_3\oplus_3 (20)_3 = (11)_3]$$$.</p><p>Третья попытка равна $$$6$$$. Это равно текущему паролю. Поэтому система возвращает ответ $$$1$$$ и работа сделана. </p><p>Заметьте, что начальные пароли были взяты такими для наглядности объяснения. В действительности система может повести себя иначе, поскольку она адаптивна. </p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D2]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c77c09d5759f',t:'MTY5NjY2NzM5Ni42MDcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*2200"]
1543E
1543
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>В конечном счете вы победили Рэйзора и теперь считаетесь Самым Разыскиваемым уличным гонщиком. Сержант Кросс послал в смертельную погоню за вами целый полицейский отряд. К счастью, вы нашли укромное убежище, но все еще переживаете, что Кросс и его ребята в конце концов вас отыщут. Чтобы увеличить свои шансы на выживание, вы собираетесь перенастроить и перекрасить вашу BMW M3 GTR. </p><p>Машину можно представлять как <span class="tex-font-style-it">перенумерованный</span> $$$n$$$-мерный гиперкуб. Простым $$$n$$$-мерным гиперкубом называется неориентированный невзвешенный граф, построенный рекурсивно следующим образом: </p><ul> <li> Возьмите два простых $$$(n-1)$$$-мерных гиперкуба. Вершины одного из них должны быть пронумерованы числами от $$$0$$$ до $$$2^{n-1}-1$$$, а другого — от $$$2^{n-1}$$$ до $$$2^{n}-1$$$. Простой $$$0$$$-мерный гиперкуб — это одна вершина. </li><li> Добавьте ребро между вершинами $$$i$$$ и $$$i+2^{n-1}$$$ для каждого $$$0\leq i &lt; 2^{n-1}$$$. </li></ul><p>Перенумерованный $$$n$$$-мерный гиперкуб получается перестановкой номеров вершин простого $$$n$$$-мерного гиперкуба произвольным образом.</p><p>Примеры простого и перенумерованного $$$3$$$-мерных гиперкубов представлены ниже:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/b5f903d137bf77c038f02563c033184a131293f0.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Заметьте, что перенумерованный $$$n$$$-мерный гиперкуб обладает следующими свойствами:</p><ul> <li> Он содержит в точности $$$2^n$$$ вершин. </li><li> Он содержит в точности $$$n\cdot 2^{n-1}$$$ ребер. </li><li> Каждая вершина соединена ровно с $$$n$$$ другими вершинами. </li><li> Он не содержит петель и кратных ребер. </li></ul><p>Обозначим за $$$P$$$ перестановку, использованную для получения перенумерованного $$$n$$$-мерного гиперкуба, описывающего вашу машину, из простого $$$n$$$-мерного гиперкуба. Прежде чем наводить беспорядок в функциональностях машины, вы хотите найти эту перестановку, чтобы, если что-то пойдет не так, суметь восстановить машину. Но это еще не все.</p><p>У вас с собой есть $$$n$$$ различных цветов, пронумерованных от $$$0$$$ до $$$n-1$$$. Вы хотите покрасить вершины перенумерованного $$$n$$$-мерного гиперкуба таким образом, чтобы для каждой вершины $$$u$$$, удовлетворяющей $$$0\leq u &lt; 2^n$$$, и каждого цвета $$$c$$$, удовлетворяющего $$$0\leq c &lt; n$$$, существовала хотя бы одна вершина $$$v$$$, соседняя с $$$u$$$ и покрашенная в цвет $$$c$$$. Иными словами, из каждой вершины должно быть возможно перейти в вершину любого цвета ровно по одному ребру. </p><p>Дан перенумерованный $$$n$$$-мерный гиперкуб, найдите любые допустимые перестановку $$$P$$$ и покраску.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1\leq t\leq 4096$$$) — количество наборов входных данных. </p><p>Для каждого набора входных данных первая строка содержит одно целое число $$$n$$$ ($$$1\leq n\leq 16$$$).</p><p>Каждая из последующих $$$n\cdot 2^{n-1}$$$ строк содержит два целых числа $$$u$$$ и $$$v$$$ ($$$0\leq u, v &lt; 2^n$$$), означающее, что вершины $$$u$$$ и $$$v$$$ соединены ребром.</p><p>Гарантируется, что граф, описанный во входных данных, задает перенумерованный $$$n$$$-мерный гиперкуб. </p><p>Также гарантируется, что сумма $$$2^n$$$ по всем наборам входных данных не превосходит $$$2^{16}=65\,536$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите две строки.</p><p>В первой строке выведите любую перестановку $$$P$$$ длины $$$2^n$$$, которая может быть использована для получения перенумерованного $$$n$$$-мерного гиперкуба, данного во входных данных, из простого $$$n$$$-мерного гиперкуба. Два перенумерованных гиперкуба считаются одинаковыми, если они имеют одинаковый набор ребер. Если возможно несколько ответов, выведите любой из них. </p><p>Во второй строке выведите покраску. Если не существует покраски, удовлетворяющей условиям, выведите $$$-1$$$. В противном случае напечатайте одну строку, содержащую $$$2^n$$$ целых чисел, разделенных пробелом. $$$i$$$-е число должно быть равно цвету вершины с номером $$$(i-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 1 0 1 2 0 1 1 2 2 3 3 0 3 0 1 0 5 0 7 1 2 1 4 2 5 2 6 3 5 3 6 3 7 4 6 4 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 0 0 0 1 3 2 0 0 1 1 5 3 0 7 2 6 1 4 -1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Покраска и перенумерованный гиперкуб для первого набора входных данных представлены ниже: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f26ce3063c6ee0d1b734f76174ce420b12c1d26f.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center> <p>Покраска и перенумерованный гиперкуб для второго набора входных данных представлены ниже: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/2353e2fa204e340b7cc87ace913ec2b3471e78b1.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center> <p>Перенумерованный гиперкуб для третьего набора дан в условии задачи. Однако, можно показать, что не существует покраски, удовлетворяющей всем условиям. Заметьте, что некоторые другие перестановки, например, $$$[0, 5, 7, 3, 1, 2, 4, 6]$$$ и $$$[0, 1, 5, 2, 7, 4, 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="692e3f3a5ac7cf121a2c976a243dc473"/> <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="c7ad42e2069dd62dfaa44a437fdde403b10c950f"/> <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='692e3f3a5ac7cf121a2c976a243dc473'>&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%2F1543%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='692e3f3a5ac7cf121a2c976a243dc473'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1543">Codeforces Round 730 (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='692e3f3a5ac7cf121a2c976a243dc473'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1543/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Разделяй и властвуй"> разделяй и властвуй </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *2700 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='692e3f3a5ac7cf121a2c976a243dc473'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1038890"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='692e3f3a5ac7cf121a2c976a243dc473'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1038890"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92543" title="Codeforces Round #730 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13977" resourceName="Codeforces Round #730 (Div. 2)" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/92582" title="Codeforces Round #730 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13988" resourceName="Codeforces Round #730 (Div. 2) Editorial" resourceManual="true" src="//codeforces.org/s/86568/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1543">Задачи</a></li> <li><a href="/contest/1543/submit">Отослать</a></li> <li><a href="/contest/1543/my">Мои посылки</a></li> <li><a href="/contest/1543/status">Статус</a></li> <li><a href="/contest/1543/hacks">Взломы</a></li> <li><a href="/contest/1543/room/1">Комната</a></li> <li><a href="/contest/1543/standings">Положение</a></li> <li><a href="/contest/1543/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9b5a0352e301fd79d7cf1f969f220f787a4d897c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>В конечном счете вы победили Рэйзора и теперь считаетесь Самым Разыскиваемым уличным гонщиком. Сержант Кросс послал в смертельную погоню за вами целый полицейский отряд. К счастью, вы нашли укромное убежище, но все еще переживаете, что Кросс и его ребята в конце концов вас отыщут. Чтобы увеличить свои шансы на выживание, вы собираетесь перенастроить и перекрасить вашу BMW M3 GTR. </p><p>Машину можно представлять как <span class="tex-font-style-it">перенумерованный</span> $$$n$$$-мерный гиперкуб. Простым $$$n$$$-мерным гиперкубом называется неориентированный невзвешенный граф, построенный рекурсивно следующим образом: </p><ul> <li> Возьмите два простых $$$(n-1)$$$-мерных гиперкуба. Вершины одного из них должны быть пронумерованы числами от $$$0$$$ до $$$2^{n-1}-1$$$, а другого — от $$$2^{n-1}$$$ до $$$2^{n}-1$$$. Простой $$$0$$$-мерный гиперкуб — это одна вершина. </li><li> Добавьте ребро между вершинами $$$i$$$ и $$$i+2^{n-1}$$$ для каждого $$$0\leq i &lt; 2^{n-1}$$$. </li></ul><p>Перенумерованный $$$n$$$-мерный гиперкуб получается перестановкой номеров вершин простого $$$n$$$-мерного гиперкуба произвольным образом.</p><p>Примеры простого и перенумерованного $$$3$$$-мерных гиперкубов представлены ниже:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/b5f903d137bf77c038f02563c033184a131293f0.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Заметьте, что перенумерованный $$$n$$$-мерный гиперкуб обладает следующими свойствами:</p><ul> <li> Он содержит в точности $$$2^n$$$ вершин. </li><li> Он содержит в точности $$$n\cdot 2^{n-1}$$$ ребер. </li><li> Каждая вершина соединена ровно с $$$n$$$ другими вершинами. </li><li> Он не содержит петель и кратных ребер. </li></ul><p>Обозначим за $$$P$$$ перестановку, использованную для получения перенумерованного $$$n$$$-мерного гиперкуба, описывающего вашу машину, из простого $$$n$$$-мерного гиперкуба. Прежде чем наводить беспорядок в функциональностях машины, вы хотите найти эту перестановку, чтобы, если что-то пойдет не так, суметь восстановить машину. Но это еще не все.</p><p>У вас с собой есть $$$n$$$ различных цветов, пронумерованных от $$$0$$$ до $$$n-1$$$. Вы хотите покрасить вершины перенумерованного $$$n$$$-мерного гиперкуба таким образом, чтобы для каждой вершины $$$u$$$, удовлетворяющей $$$0\leq u &lt; 2^n$$$, и каждого цвета $$$c$$$, удовлетворяющего $$$0\leq c &lt; n$$$, существовала хотя бы одна вершина $$$v$$$, соседняя с $$$u$$$ и покрашенная в цвет $$$c$$$. Иными словами, из каждой вершины должно быть возможно перейти в вершину любого цвета ровно по одному ребру. </p><p>Дан перенумерованный $$$n$$$-мерный гиперкуб, найдите любые допустимые перестановку $$$P$$$ и покраску.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1\leq t\leq 4096$$$) — количество наборов входных данных. </p><p>Для каждого набора входных данных первая строка содержит одно целое число $$$n$$$ ($$$1\leq n\leq 16$$$).</p><p>Каждая из последующих $$$n\cdot 2^{n-1}$$$ строк содержит два целых числа $$$u$$$ и $$$v$$$ ($$$0\leq u, v &lt; 2^n$$$), означающее, что вершины $$$u$$$ и $$$v$$$ соединены ребром.</p><p>Гарантируется, что граф, описанный во входных данных, задает перенумерованный $$$n$$$-мерный гиперкуб. </p><p>Также гарантируется, что сумма $$$2^n$$$ по всем наборам входных данных не превосходит $$$2^{16}=65\,536$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите две строки.</p><p>В первой строке выведите любую перестановку $$$P$$$ длины $$$2^n$$$, которая может быть использована для получения перенумерованного $$$n$$$-мерного гиперкуба, данного во входных данных, из простого $$$n$$$-мерного гиперкуба. Два перенумерованных гиперкуба считаются одинаковыми, если они имеют одинаковый набор ребер. Если возможно несколько ответов, выведите любой из них. </p><p>Во второй строке выведите покраску. Если не существует покраски, удовлетворяющей условиям, выведите $$$-1$$$. В противном случае напечатайте одну строку, содержащую $$$2^n$$$ целых чисел, разделенных пробелом. $$$i$$$-е число должно быть равно цвету вершины с номером $$$(i-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 1 0 1 2 0 1 1 2 2 3 3 0 3 0 1 0 5 0 7 1 2 1 4 2 5 2 6 3 5 3 6 3 7 4 6 4 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 0 0 0 1 3 2 0 0 1 1 5 3 0 7 2 6 1 4 -1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Покраска и перенумерованный гиперкуб для первого набора входных данных представлены ниже: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f26ce3063c6ee0d1b734f76174ce420b12c1d26f.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center> <p>Покраска и перенумерованный гиперкуб для второго набора входных данных представлены ниже: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/2353e2fa204e340b7cc87ace913ec2b3471e78b1.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center> <p>Перенумерованный гиперкуб для третьего набора дан в условии задачи. Однако, можно показать, что не существует покраски, удовлетворяющей всем условиям. Заметьте, что некоторые другие перестановки, например, $$$[0, 5, 7, 3, 1, 2, 4, 6]$$$ и $$$[0, 1, 5, 2, 7, 4, 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 11:29: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:'8124c7848f6b75a3',t:'MTY5NjY2NzM5Ny45OTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0413\u0440\u0430\u0444\u044b", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\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\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0433\u0440\u0430\u0444\u044b", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "*2700"]
1544A
1544
A
ru
A. Двоично-десятичные
<div class="problem-statement"><div class="header"><div class="title">A. Двоично-десятичные</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Назовем число <span class="tex-font-style-it">двоично-десятичным</span>, если оно целое, положительное, и все его цифры в десятичной системе счисления равны либо $$$0$$$, либо $$$1$$$. Например, $$$1\,010\,111$$$ — двоично-десятичное число, а $$$10\,201$$$ и $$$787\,788$$$ — нет.</p><p>Дано число $$$n$$$, вас просят представить $$$n$$$ как сумму нескольких (не обязательно различных) двоично-десятичных чисел. Найдите минимальное необходимое для этого количество двоично-десятичных чисел.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Во входных данных находятся несколько наборов входных данных. В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных задан на отдельной строке и содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^9$$$) — число, которое нужно представить в виде суммы.</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 121 5 1000000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 5 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных число $$$121$$$ можно представить, например, как $$$121 = 110 + 11$$$ или $$$121 = 111 + 10$$$.</p><p>Во втором наборе входных данных число $$$5$$$ можно представить как $$$5 = 1 + 1 + 1 + 1 + 1$$$.</p><p>В третьем наборе входных данных число $$$1\,000\,000\,000$$$ само является двоично-десятичным, поэтому ответ равен $$$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="6899884f05da9e32128c6d3a48b123d8"/> <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="3656e17289c8c70050c1f01fdb01de047e253b00"/> <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='6899884f05da9e32128c6d3a48b123d8'>&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="position:relative;bottom:4px;"><a href="/vkcup2021"><img src="https://assets.codeforces.com/images/vkcup21-500x70-1.jpg"/></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%2F1544%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='6899884f05da9e32128c6d3a48b123d8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1544">VK Cup 2021 - Отборочный раунд (Engine)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </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/1544/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *800 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6899884f05da9e32128c6d3a48b123d8'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1049160"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6899884f05da9e32128c6d3a48b123d8'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1049160"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92916" title="VK Cup 2021 — Отбор (Engine) и Codeforces Round #733 (Div. 1 + Div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14034:14035" 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/92951" title="Codeforces Round #733 Editorial (all problems)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14040" resourceName="Codeforces Round #733 Editorial (all problems)" resourceManual="true" src="//codeforces.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/1544">Задачи</a></li> <li><a href="/contest/1544/submit">Отослать</a></li> <li><a href="/contest/1544/my">Мои посылки</a></li> <li><a href="/contest/1544/status">Статус</a></li> <li><a href="/contest/1544/hacks">Взломы</a></li> <li><a href="/contest/1544/room/1">Комната</a></li> <li><a href="/contest/1544/standings">Положение</a></li> <li><a href="/contest/1544/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0f341757e9eb13edfbeab8c8257755492f609c50"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Назовем число <span class="tex-font-style-it">двоично-десятичным</span>, если оно целое, положительное, и все его цифры в десятичной системе счисления равны либо $$$0$$$, либо $$$1$$$. Например, $$$1\,010\,111$$$ — двоично-десятичное число, а $$$10\,201$$$ и $$$787\,788$$$ — нет.</p><p>Дано число $$$n$$$, вас просят представить $$$n$$$ как сумму нескольких (не обязательно различных) двоично-десятичных чисел. Найдите минимальное необходимое для этого количество двоично-десятичных чисел.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Во входных данных находятся несколько наборов входных данных. В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных задан на отдельной строке и содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^9$$$) — число, которое нужно представить в виде суммы.</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 121 5 1000000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 5 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных число $$$121$$$ можно представить, например, как $$$121 = 110 + 11$$$ или $$$121 = 111 + 10$$$.</p><p>Во втором наборе входных данных число $$$5$$$ можно представить как $$$5 = 1 + 1 + 1 + 1 + 1$$$.</p><p>В третьем наборе входных данных число $$$1\,000\,000\,000$$$ само является двоично-десятичным, поэтому ответ равен $$$1$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:29: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:'8124c78d1b7116c3',t:'MTY5NjY2NzM5OS4zODEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*800"]
1544B
1544
B
ru
B. Расставьте тарелки
<div class="problem-statement"><div class="header"><div class="title">B. Расставьте тарелки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В честь вашего дня рождения вы подготовили праздничный стол! Теперь вы хотите посадить за него как можно больше гостей.</p><p>Стол можно схематично представить в виде прямоугольника с высотой $$$h$$$ и шириной $$$w$$$, разбитого на $$$h \times w$$$ ячеек. Будем обозначать через $$$(i, j)$$$ ячейку в $$$i$$$-й строке и $$$j$$$-м столбце прямоугольника ($$$1 \le i \le h$$$; $$$1 \le j \le w$$$).</p><p>В каждую ячейку можно либо поставить тарелку для гостя, либо оставить её пустой.</p><p>Поскольку гостя нужно посадить рядом со своей тарелкой, можно ставить тарелки только на границу стола — в первую или последнюю строку прямоугольника, либо в первый или последний столбец. Формально, для любой ячейки $$$(i, j)$$$, в которую ставится тарелка, должно выполняться хотя бы одно из следующих условий: $$$i = 1$$$, $$$i = h$$$, $$$j = 1$$$, $$$j = w$$$.</p><p>Чтобы гостям было максимально комфортно, никакие две тарелки не должны находиться в ячейках, имеющих общую сторону или угол. Иными словами, если в ячейке $$$(i, j)$$$ находится тарелка, нельзя ставить тарелки в ячейки $$$(i - 1, j)$$$, $$$(i, j - 1)$$$, $$$(i + 1, j)$$$, $$$(i, j + 1)$$$, $$$(i - 1, j - 1)$$$, $$$(i - 1, j + 1)$$$, $$$(i + 1, j - 1)$$$, $$$(i + 1, j + 1)$$$.</p><p>Поставьте как можно больше тарелок на стол, не нарушая описанные выше условия.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Во входных данных находятся несколько наборов входных данных. В первой строке задано целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>Каждая из следующих $$$t$$$ строк описывает один набор входных данных и содержит два целых числа $$$h$$$ и $$$w$$$ ($$$3 \le h, w \le 20$$$) — высоту и ширину стола.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите $$$h$$$ строк по $$$w$$$ символов каждый. Символ $$$j$$$ в строке $$$i$$$ должен быть равен $$$1$$$, если в ячейку $$$(i, j)$$$ ставится тарелка, и $$$0$$$ в противном случае. Если существует несколько решений, выведите любое из них.</p><p>Все тарелки должны стоять на границе стола. Никакие две тарелки не могут стоять в ячейках, соседних по стороне или углу. Число тарелок, выставленных на стол при этих условиях, должно быть максимальным возможным.</p><p>Разрешается выводить дополнительные пустые строки.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 5 4 4 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10101 00000 10101 0100 0001 1000 0010 010101 000000 100001 000000 101010 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере представлен единственный способ расставить $$$6$$$ тарелок на стол в первом наборе входных данных.</p><p>Во втором наборе входных данных есть много способов расставить $$$4$$$ тарелки, приведён один из них. </p><p>Поставить больше $$$6$$$ тарелок в первом наборе входных данных или $$$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="4baefdc2c2b5707e28880f730ddcc687"/> <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="3656e17289c8c70050c1f01fdb01de047e253b00"/> <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='4baefdc2c2b5707e28880f730ddcc687'>&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="position:relative;bottom:4px;"><a href="/vkcup2021"><img src="https://assets.codeforces.com/images/vkcup21-500x70-1.jpg"/></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%2F1544%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='4baefdc2c2b5707e28880f730ddcc687'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1544">VK Cup 2021 - Отборочный раунд (Engine)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </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/1544/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *800 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4baefdc2c2b5707e28880f730ddcc687'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1049161"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4baefdc2c2b5707e28880f730ddcc687'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1049161"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92916" title="VK Cup 2021 — Отбор (Engine) и Codeforces Round #733 (Div. 1 + Div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14034:14035" 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/92951" title="Codeforces Round #733 Editorial (all problems)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14040" resourceName="Codeforces Round #733 Editorial (all problems)" resourceManual="true" src="//codeforces.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/1544">Задачи</a></li> <li><a href="/contest/1544/submit">Отослать</a></li> <li><a href="/contest/1544/my">Мои посылки</a></li> <li><a href="/contest/1544/status">Статус</a></li> <li><a href="/contest/1544/hacks">Взломы</a></li> <li><a href="/contest/1544/room/1">Комната</a></li> <li><a href="/contest/1544/standings">Положение</a></li> <li><a href="/contest/1544/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f8064fa56b7b2dfda4390312fbf272f380d73f13"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>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>Стол можно схематично представить в виде прямоугольника с высотой $$$h$$$ и шириной $$$w$$$, разбитого на $$$h \times w$$$ ячеек. Будем обозначать через $$$(i, j)$$$ ячейку в $$$i$$$-й строке и $$$j$$$-м столбце прямоугольника ($$$1 \le i \le h$$$; $$$1 \le j \le w$$$).</p><p>В каждую ячейку можно либо поставить тарелку для гостя, либо оставить её пустой.</p><p>Поскольку гостя нужно посадить рядом со своей тарелкой, можно ставить тарелки только на границу стола — в первую или последнюю строку прямоугольника, либо в первый или последний столбец. Формально, для любой ячейки $$$(i, j)$$$, в которую ставится тарелка, должно выполняться хотя бы одно из следующих условий: $$$i = 1$$$, $$$i = h$$$, $$$j = 1$$$, $$$j = w$$$.</p><p>Чтобы гостям было максимально комфортно, никакие две тарелки не должны находиться в ячейках, имеющих общую сторону или угол. Иными словами, если в ячейке $$$(i, j)$$$ находится тарелка, нельзя ставить тарелки в ячейки $$$(i - 1, j)$$$, $$$(i, j - 1)$$$, $$$(i + 1, j)$$$, $$$(i, j + 1)$$$, $$$(i - 1, j - 1)$$$, $$$(i - 1, j + 1)$$$, $$$(i + 1, j - 1)$$$, $$$(i + 1, j + 1)$$$.</p><p>Поставьте как можно больше тарелок на стол, не нарушая описанные выше условия.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Во входных данных находятся несколько наборов входных данных. В первой строке задано целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>Каждая из следующих $$$t$$$ строк описывает один набор входных данных и содержит два целых числа $$$h$$$ и $$$w$$$ ($$$3 \le h, w \le 20$$$) — высоту и ширину стола.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите $$$h$$$ строк по $$$w$$$ символов каждый. Символ $$$j$$$ в строке $$$i$$$ должен быть равен $$$1$$$, если в ячейку $$$(i, j)$$$ ставится тарелка, и $$$0$$$ в противном случае. Если существует несколько решений, выведите любое из них.</p><p>Все тарелки должны стоять на границе стола. Никакие две тарелки не могут стоять в ячейках, соседних по стороне или углу. Число тарелок, выставленных на стол при этих условиях, должно быть максимальным возможным.</p><p>Разрешается выводить дополнительные пустые строки.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 5 4 4 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10101 00000 10101 0100 0001 1000 0010 010101 000000 100001 000000 101010 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере представлен единственный способ расставить $$$6$$$ тарелок на стол в первом наборе входных данных.</p><p>Во втором наборе входных данных есть много способов расставить $$$4$$$ тарелки, приведён один из них. </p><p>Поставить больше $$$6$$$ тарелок в первом наборе входных данных или $$$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 11:30: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:'8124c795cb969da4',t:'MTY5NjY2NzQwMC42NTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*800"]
1544C
1544
C
ru
C. Погоня
<div class="problem-statement"><div class="header"><div class="title">C. Погоня</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы и ваш друг Илья участвуете в личном соревновании по программированию, состоящем из множества этапов. За каждый этап участник может получить любое целое число баллов от $$$0$$$ до $$$100$$$ включительно, независимо от других участников.</p><p>Баллы, набранные участниками в отдельных этапах, используются для формирования суммарных результатов соревнования. Пусть к некоторому моменту времени прошло $$$k$$$ этапов. Тогда для каждого участника выбирается $$$k - \lfloor \frac{k}{4} \rfloor$$$ этапов, на которых он набрал наибольшее число баллов, и суммируются баллы на них. Полученное число и является суммарным результатом участника. (Здесь $$$\lfloor t \rfloor$$$ обозначает округление вниз до наибольшего целого числа, не большего $$$t$$$.)</p><p>Например, пусть прошло $$$9$$$ этапов, на которых вы набрали баллы $$$50, 30, 50, 50, 100, 10, 30, 100, 50$$$. Сначала выбираются $$$7$$$ этапов, на которых вы набрали наибольшее число баллов: например, это могут быть все этапы, кроме $$$2$$$-го и $$$6$$$-го. Тогда ваш суммарный результат равен $$$50 + 50 + 50 + 100 + 30 + 100 + 50 = 430$$$.</p><p>К данному моменту прошло $$$n$$$ этапов, и вам известны ваши баллы и баллы Ильи на каждом из этих этапов. Однако сколько ещё этапов будет в соревновании, неизвестно. Вам интересно, какое наименьшее число этапов ещё должно пройти, чтобы ваш результат хотя бы теоретически смог оказаться больше или равен результату Ильи. Найдите это число!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Во входных данных находятся несколько наборов входных данных. В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных. Далее следуют наборы входных данных.</p><p>Первая строка набора входных данных содержит целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — число прошедших этапов соревнования.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 100$$$) — ваши баллы на прошедших этапах.</p><p>Третья строка содержит $$$n$$$ целых чисел $$$b_1, b_2, \ldots, b_n$$$ ($$$0 \le b_i \le 100$$$) — баллы Ильи на прошедших этапах.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — наименьшее число этапов, через которое ваш результат может оказаться больше или равен результату Ильи.</p><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> 5 1 100 0 1 0 100 4 20 30 40 50 100 100 100 100 4 10 20 30 40 100 100 100 100 7 7 59 62 52 27 31 55 33 35 50 98 83 80 64 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 3 4 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных вы набрали $$$100$$$ баллов на единственном прошедшем этапе, а Илья — $$$0$$$. Значит, ваш суммарный результат ($$$100$$$) и так не хуже результата Ильи ($$$0$$$).</p><p>Во втором наборе входных данных вы набрали $$$0$$$ баллов на первом этапе, а Илья — $$$100$$$. Достаточно одного этапа с противоположным результатом, чтобы суммарный результат вас обоих стал равен $$$100$$$.</p><p>В третьем наборе входных данных ваш суммарный результат равен $$$30 + 40 + 50 = 120$$$, а Ильи — $$$100 + 100 + 100 = 300$$$. После трёх дополнительных этапов ваш результат может стать равен $$$420$$$, а Ильи — $$$400$$$.</p><p>В четвёртом наборе входных данных после четырёх дополнительных этапов ваш результат может стать равен $$$470$$$, а Ильи — $$$400$$$. Трёх этапов недостаточно.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="22f39e1be091097f5619d72f88b7ab57"/> <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="3656e17289c8c70050c1f01fdb01de047e253b00"/> <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='22f39e1be091097f5619d72f88b7ab57'>&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="position:relative;bottom:4px;"><a href="/vkcup2021"><img src="https://assets.codeforces.com/images/vkcup21-500x70-1.jpg"/></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%2F1544%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='22f39e1be091097f5619d72f88b7ab57'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1544">VK Cup 2021 - Отборочный раунд (Engine)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </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/1544/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='22f39e1be091097f5619d72f88b7ab57'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1049162"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='22f39e1be091097f5619d72f88b7ab57'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1049162"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92916" title="VK Cup 2021 — Отбор (Engine) и Codeforces Round #733 (Div. 1 + Div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14034:14035" 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/92951" title="Codeforces Round #733 Editorial (all problems)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14040" resourceName="Codeforces Round #733 Editorial (all problems)" resourceManual="true" src="//codeforces.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/1544">Задачи</a></li> <li><a href="/contest/1544/submit">Отослать</a></li> <li><a href="/contest/1544/my">Мои посылки</a></li> <li><a href="/contest/1544/status">Статус</a></li> <li><a href="/contest/1544/hacks">Взломы</a></li> <li><a href="/contest/1544/room/1">Комната</a></li> <li><a href="/contest/1544/standings">Положение</a></li> <li><a href="/contest/1544/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_a79340c8874d3a2009fd864225ad45dce27968b6"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>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>Вы и ваш друг Илья участвуете в личном соревновании по программированию, состоящем из множества этапов. За каждый этап участник может получить любое целое число баллов от $$$0$$$ до $$$100$$$ включительно, независимо от других участников.</p><p>Баллы, набранные участниками в отдельных этапах, используются для формирования суммарных результатов соревнования. Пусть к некоторому моменту времени прошло $$$k$$$ этапов. Тогда для каждого участника выбирается $$$k - \lfloor \frac{k}{4} \rfloor$$$ этапов, на которых он набрал наибольшее число баллов, и суммируются баллы на них. Полученное число и является суммарным результатом участника. (Здесь $$$\lfloor t \rfloor$$$ обозначает округление вниз до наибольшего целого числа, не большего $$$t$$$.)</p><p>Например, пусть прошло $$$9$$$ этапов, на которых вы набрали баллы $$$50, 30, 50, 50, 100, 10, 30, 100, 50$$$. Сначала выбираются $$$7$$$ этапов, на которых вы набрали наибольшее число баллов: например, это могут быть все этапы, кроме $$$2$$$-го и $$$6$$$-го. Тогда ваш суммарный результат равен $$$50 + 50 + 50 + 100 + 30 + 100 + 50 = 430$$$.</p><p>К данному моменту прошло $$$n$$$ этапов, и вам известны ваши баллы и баллы Ильи на каждом из этих этапов. Однако сколько ещё этапов будет в соревновании, неизвестно. Вам интересно, какое наименьшее число этапов ещё должно пройти, чтобы ваш результат хотя бы теоретически смог оказаться больше или равен результату Ильи. Найдите это число!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Во входных данных находятся несколько наборов входных данных. В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных. Далее следуют наборы входных данных.</p><p>Первая строка набора входных данных содержит целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — число прошедших этапов соревнования.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 100$$$) — ваши баллы на прошедших этапах.</p><p>Третья строка содержит $$$n$$$ целых чисел $$$b_1, b_2, \ldots, b_n$$$ ($$$0 \le b_i \le 100$$$) — баллы Ильи на прошедших этапах.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — наименьшее число этапов, через которое ваш результат может оказаться больше или равен результату Ильи.</p><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> 5 1 100 0 1 0 100 4 20 30 40 50 100 100 100 100 4 10 20 30 40 100 100 100 100 7 7 59 62 52 27 31 55 33 35 50 98 83 80 64 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 3 4 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных вы набрали $$$100$$$ баллов на единственном прошедшем этапе, а Илья — $$$0$$$. Значит, ваш суммарный результат ($$$100$$$) и так не хуже результата Ильи ($$$0$$$).</p><p>Во втором наборе входных данных вы набрали $$$0$$$ баллов на первом этапе, а Илья — $$$100$$$. Достаточно одного этапа с противоположным результатом, чтобы суммарный результат вас обоих стал равен $$$100$$$.</p><p>В третьем наборе входных данных ваш суммарный результат равен $$$30 + 40 + 50 = 120$$$, а Ильи — $$$100 + 100 + 100 = 300$$$. После трёх дополнительных этапов ваш результат может стать равен $$$420$$$, а Ильи — $$$400$$$.</p><p>В четвёртом наборе входных данных после четырёх дополнительных этапов ваш результат может стать равен $$$470$$$, а Ильи — $$$400$$$. Трёх этапов недостаточно.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c79deb4116ec',t:'MTY5NjY2NzQwMS45ODgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "*1200"]
1544D
1544
D
ru
D. Секретный Санта
<div class="problem-statement"><div class="header"><div class="title">D. Секретный Санта</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В компании ВКонтакте в декабре традиционно проводится мероприятие под названием «Секретный Санта». Суть его в следующем.</p><p>В мероприятии участвуют $$$n$$$ сотрудников, пронумерованных от $$$1$$$ до $$$n$$$. Каждому сотруднику $$$i$$$ назначается другой сотрудник $$$b_i$$$, которому сотрудник $$$i$$$ должен сделать новогодний подарок. При этом каждый сотрудник назначается ровно одному другому сотруднику, и никто не назначается сам себе (но возможно, что два сотрудника окажутся назначены друг другу). Формально, все $$$b_i$$$ должны быть различными целыми числами от $$$1$$$ до $$$n$$$, и для любого $$$i$$$ должно выполняться $$$b_i \ne i$$$.</p><p>Как правило, назначение происходит случайным образом. Но в качестве эксперимента у участников мероприятия спросили, кому бы они хотели сделать подарок. Каждый сотрудник $$$i$$$ сказал, что желает сделать подарок сотруднику $$$a_i$$$.</p><p>Найдите такое корректное назначение $$$b$$$, что как можно больше пожеланий сотрудников окажется выполнено.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Во входных данных находятся несколько наборов входных данных. В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 10^5$$$) — количество наборов входных данных. Далее следуют наборы входных данных.</p><p>Каждый набор входных данных задан в двух строках. Первая строка содержит целое число $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — число участников мероприятия.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$; $$$a_i \ne i$$$) — пожелания сотрудников в порядке от $$$1$$$-го до $$$n$$$-го.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите две строки.</p><p>В первой строке выведите целое число $$$k$$$ ($$$0 \le k \le n$$$) — число выполненных пожеланий в вашем назначении.</p><p>Во второй строке выведите $$$n$$$ различных целых чисел $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$; $$$b_i \ne i$$$) — номера сотрудников, назначенных сотрудникам $$$1, 2, \ldots, n$$$.</p><p>Число $$$k$$$ должно быть равно числу индексов $$$i$$$ таких, что $$$a_i = b_i$$$, и должно быть максимальным возможным. Если существует несколько решений, выведите любое из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 3 2 1 2 7 6 4 6 2 4 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 1 2 4 6 4 7 2 3 5 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных существует два корректных назначения — $$$[3, 1, 2]$$$ и $$$[2, 3, 1]$$$. В первом случае будет выполнено два пожелания, а во втором — одно. Таким образом, $$$k = 2$$$, и верным ответом является только назначение $$$[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="912c0148c9cc8cc2dd6ae8ac670ada44"/> <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="3656e17289c8c70050c1f01fdb01de047e253b00"/> <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='912c0148c9cc8cc2dd6ae8ac670ada44'>&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="position:relative;bottom:4px;"><a href="/vkcup2021"><img src="https://assets.codeforces.com/images/vkcup21-500x70-1.jpg"/></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%2F1544%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='912c0148c9cc8cc2dd6ae8ac670ada44'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1544">VK Cup 2021 - Отборочный раунд (Engine)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </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/1544/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='912c0148c9cc8cc2dd6ae8ac670ada44'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1049163"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='912c0148c9cc8cc2dd6ae8ac670ada44'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1049163"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92916" title="VK Cup 2021 — Отбор (Engine) и Codeforces Round #733 (Div. 1 + Div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14034:14035" 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/92951" title="Codeforces Round #733 Editorial (all problems)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14040" resourceName="Codeforces Round #733 Editorial (all problems)" resourceManual="true" src="//codeforces.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/1544">Задачи</a></li> <li><a href="/contest/1544/submit">Отослать</a></li> <li><a href="/contest/1544/my">Мои посылки</a></li> <li><a href="/contest/1544/status">Статус</a></li> <li><a href="/contest/1544/hacks">Взломы</a></li> <li><a href="/contest/1544/room/1">Комната</a></li> <li><a href="/contest/1544/standings">Положение</a></li> <li><a href="/contest/1544/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2c422816e1ce89839897c4717ba4a4da2cee4e5c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Секретный Санта</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В компании ВКонтакте в декабре традиционно проводится мероприятие под названием «Секретный Санта». Суть его в следующем.</p><p>В мероприятии участвуют $$$n$$$ сотрудников, пронумерованных от $$$1$$$ до $$$n$$$. Каждому сотруднику $$$i$$$ назначается другой сотрудник $$$b_i$$$, которому сотрудник $$$i$$$ должен сделать новогодний подарок. При этом каждый сотрудник назначается ровно одному другому сотруднику, и никто не назначается сам себе (но возможно, что два сотрудника окажутся назначены друг другу). Формально, все $$$b_i$$$ должны быть различными целыми числами от $$$1$$$ до $$$n$$$, и для любого $$$i$$$ должно выполняться $$$b_i \ne i$$$.</p><p>Как правило, назначение происходит случайным образом. Но в качестве эксперимента у участников мероприятия спросили, кому бы они хотели сделать подарок. Каждый сотрудник $$$i$$$ сказал, что желает сделать подарок сотруднику $$$a_i$$$.</p><p>Найдите такое корректное назначение $$$b$$$, что как можно больше пожеланий сотрудников окажется выполнено.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Во входных данных находятся несколько наборов входных данных. В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 10^5$$$) — количество наборов входных данных. Далее следуют наборы входных данных.</p><p>Каждый набор входных данных задан в двух строках. Первая строка содержит целое число $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — число участников мероприятия.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$; $$$a_i \ne i$$$) — пожелания сотрудников в порядке от $$$1$$$-го до $$$n$$$-го.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите две строки.</p><p>В первой строке выведите целое число $$$k$$$ ($$$0 \le k \le n$$$) — число выполненных пожеланий в вашем назначении.</p><p>Во второй строке выведите $$$n$$$ различных целых чисел $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$; $$$b_i \ne i$$$) — номера сотрудников, назначенных сотрудникам $$$1, 2, \ldots, n$$$.</p><p>Число $$$k$$$ должно быть равно числу индексов $$$i$$$ таких, что $$$a_i = b_i$$$, и должно быть максимальным возможным. Если существует несколько решений, выведите любое из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 3 2 1 2 7 6 4 6 2 4 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 1 2 4 6 4 7 2 3 5 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных существует два корректных назначения — $$$[3, 1, 2]$$$ и $$$[2, 3, 1]$$$. В первом случае будет выполнено два пожелания, а во втором — одно. Таким образом, $$$k = 2$$$, и верным ответом является только назначение $$$[3, 1, 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 11:30: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:'8124c7a64a3d9d39',t:'MTY5NjY2NzQwMy4zMDEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1600"]
1544E
1544
E
ru
E. Минимакс
<div class="problem-statement"><div class="header"><div class="title">E. Минимакс</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Префикс-функция</span> от строки $$$t = t_1 t_2 \ldots t_n$$$ и позиции $$$i$$$ в ней — это длина $$$k$$$ наибольшего собственного (не равного всей подстроке) префикса подстроки $$$t_1 t_2 \ldots t_i$$$, который одновременно является суффиксом этой подстроки.</p><p>Например, для строки $$$t = $$$ <span class="tex-font-style-tt">abacaba</span> значения префикс-функции от позиций $$$1, 2, \ldots, 7$$$ равны $$$[0, 0, 1, 0, 1, 2, 3]$$$.</p><p>Введём функцию $$$f(t)$$$, равную <span class="tex-font-style-it">максимальному</span> значению префикс-функции строки $$$t$$$ по всем её позициям. Например, $$$f($$$<span class="tex-font-style-tt">abacaba</span>$$$) = 3$$$.</p><p>Вам дана строка $$$s$$$. Переставьте её символы произвольным образом, чтобы получить строку $$$t$$$ (количество вхождений любого символа в строки $$$s$$$ и $$$t$$$ должно совпадать). Значение $$$f(t)$$$ должно быть <span class="tex-font-style-it">минимальным</span> возможным. Среди всех вариантов минимизировать $$$f(t)$$$ выберите тот, где строка $$$t$$$ <span class="tex-font-style-it">лексикографически минимальна</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Во входных данных находятся несколько наборов входных данных. В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 10^5$$$) — количество наборов входных данных. Далее следуют наборы входных данных.</p><p>Каждый набор входных данных состоит из одной строки $$$s$$$ ($$$1 \le |s| \le 10^5$$$), состоящей из строчных латинских букв.</p><p>Гарантируется, что сумма длин строк $$$s$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку $$$t$$$.</p><p>Мультимножество букв в строках $$$s$$$ и $$$t$$$ должно совпадать. Значение $$$f(t)$$$, максимума префикс-функции в строке $$$t$$$, должно быть минимальным возможным. Строка $$$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 vkcup abababa zzzzzz </pre></div><div class="output"><div class="title">Выходные данные</div><pre> ckpuv aababab zzzzzz </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Строка $$$a$$$ лексикографически меньше строки $$$b$$$, если и только если выполняется один из следующих пунктов:</p><ul><li> $$$a$$$ — префикс $$$b$$$, но $$$a \ne b$$$;</li><li> в первой позиции, где $$$a$$$ и $$$b$$$ различны, в строке $$$a$$$ находится буква, которая встречается в алфавите раньше, чем соответствующая буква в $$$b$$$.</li></ul><p>В первом наборе входных данных $$$f(t) = 0$$$ и значения префикс-функции равны $$$[0, 0, 0, 0, 0]$$$ для любой перестановки букв. Строка <span class="tex-font-style-tt">ckpuv</span> является лексикографически минимальной перестановкой букв строки <span class="tex-font-style-tt">vkcup</span>.</p><p>Во втором наборе входных данных $$$f(t) = 1$$$, значения префикс-функции равны $$$[0, 1, 0, 1, 0, 1, 0]$$$.</p><p>В третьем наборе входных данных $$$f(t) = 5$$$, значения префикс-функции равны $$$[0, 1, 2, 3, 4, 5]$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="558497c395a26b0b0468df189256ff70"/> <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="3656e17289c8c70050c1f01fdb01de047e253b00"/> <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='558497c395a26b0b0468df189256ff70'>&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="position:relative;bottom:4px;"><a href="/vkcup2021"><img src="https://assets.codeforces.com/images/vkcup21-500x70-1.jpg"/></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%2F1544%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='558497c395a26b0b0468df189256ff70'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1544">VK Cup 2021 - Отборочный раунд (Engine)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </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/1544/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='558497c395a26b0b0468df189256ff70'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1049164"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='558497c395a26b0b0468df189256ff70'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1049164"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92916" title="VK Cup 2021 — Отбор (Engine) и Codeforces Round #733 (Div. 1 + Div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14034:14035" 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/92951" title="Codeforces Round #733 Editorial (all problems)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14040" resourceName="Codeforces Round #733 Editorial (all problems)" resourceManual="true" src="//codeforces.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/1544">Задачи</a></li> <li><a href="/contest/1544/submit">Отослать</a></li> <li><a href="/contest/1544/my">Мои посылки</a></li> <li><a href="/contest/1544/status">Статус</a></li> <li><a href="/contest/1544/hacks">Взломы</a></li> <li><a href="/contest/1544/room/1">Комната</a></li> <li><a href="/contest/1544/standings">Положение</a></li> <li><a href="/contest/1544/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_6b58d9b1f7436e37a6102225daf3b23a0369fdf1"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Минимакс</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Префикс-функция</span> от строки $$$t = t_1 t_2 \ldots t_n$$$ и позиции $$$i$$$ в ней — это длина $$$k$$$ наибольшего собственного (не равного всей подстроке) префикса подстроки $$$t_1 t_2 \ldots t_i$$$, который одновременно является суффиксом этой подстроки.</p><p>Например, для строки $$$t = $$$ <span class="tex-font-style-tt">abacaba</span> значения префикс-функции от позиций $$$1, 2, \ldots, 7$$$ равны $$$[0, 0, 1, 0, 1, 2, 3]$$$.</p><p>Введём функцию $$$f(t)$$$, равную <span class="tex-font-style-it">максимальному</span> значению префикс-функции строки $$$t$$$ по всем её позициям. Например, $$$f($$$<span class="tex-font-style-tt">abacaba</span>$$$) = 3$$$.</p><p>Вам дана строка $$$s$$$. Переставьте её символы произвольным образом, чтобы получить строку $$$t$$$ (количество вхождений любого символа в строки $$$s$$$ и $$$t$$$ должно совпадать). Значение $$$f(t)$$$ должно быть <span class="tex-font-style-it">минимальным</span> возможным. Среди всех вариантов минимизировать $$$f(t)$$$ выберите тот, где строка $$$t$$$ <span class="tex-font-style-it">лексикографически минимальна</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Во входных данных находятся несколько наборов входных данных. В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 10^5$$$) — количество наборов входных данных. Далее следуют наборы входных данных.</p><p>Каждый набор входных данных состоит из одной строки $$$s$$$ ($$$1 \le |s| \le 10^5$$$), состоящей из строчных латинских букв.</p><p>Гарантируется, что сумма длин строк $$$s$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку $$$t$$$.</p><p>Мультимножество букв в строках $$$s$$$ и $$$t$$$ должно совпадать. Значение $$$f(t)$$$, максимума префикс-функции в строке $$$t$$$, должно быть минимальным возможным. Строка $$$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 vkcup abababa zzzzzz </pre></div><div class="output"><div class="title">Выходные данные</div><pre> ckpuv aababab zzzzzz </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Строка $$$a$$$ лексикографически меньше строки $$$b$$$, если и только если выполняется один из следующих пунктов:</p><ul><li> $$$a$$$ — префикс $$$b$$$, но $$$a \ne b$$$;</li><li> в первой позиции, где $$$a$$$ и $$$b$$$ различны, в строке $$$a$$$ находится буква, которая встречается в алфавите раньше, чем соответствующая буква в $$$b$$$.</li></ul><p>В первом наборе входных данных $$$f(t) = 0$$$ и значения префикс-функции равны $$$[0, 0, 0, 0, 0]$$$ для любой перестановки букв. Строка <span class="tex-font-style-tt">ckpuv</span> является лексикографически минимальной перестановкой букв строки <span class="tex-font-style-tt">vkcup</span>.</p><p>Во втором наборе входных данных $$$f(t) = 1$$$, значения префикс-функции равны $$$[0, 1, 0, 1, 0, 1, 0]$$$.</p><p>В третьем наборе входных данных $$$f(t) = 5$$$, значения префикс-функции равны $$$[0, 1, 2, 3, 4, 5]$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c7ae6b1a9da2',t:'MTY5NjY2NzQwNC42MDMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u0430\u0437\u0431\u043e\u0440 \u0432\u044b\u0440\u0430\u0436\u0435\u043d\u0438\u0439", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0440\u0430\u0437\u0431\u043e\u0440 \u0432\u044b\u0440\u0430\u0436\u0435\u043d\u0438\u0439", "\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", "*2100"]
1544F
1544
F
ru
F. Бинго
<div class="problem-statement"><div class="header"><div class="title">F. Бинго</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>7 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В предвкушении VK Fest 2021 вы составили себе табличку из $$$n$$$ строк и $$$n$$$ столбцов, и в каждую ячейку этой таблички записали некоторое событие, связанное с фестивалем, которое может произойти или нет — например, удастся ли вам выиграть на фестивале приз, или пойдёт ли дождь.</p><p>Алгоритмы предсказания ВКонтакте уже оценили для каждого события вероятность того, что оно произойдёт. Событие в строке $$$i$$$ и столбце $$$j$$$ произойдёт с вероятностью $$$a_{i, j} \cdot 10^{-4}$$$. При этом все события совместно независимы друг от друга.</p><p>Назовём табличку с событиями <span class="tex-font-style-it">выигрышной</span>, если найдётся такая линия, на которой произойдут все $$$n$$$ событий. Линией считается любая горизонталь (ячейки $$$(i, 1), (i, 2), \ldots, (i, n)$$$ для некоторого $$$i$$$), любая вертикаль (ячейки $$$(1, j), (2, j), \ldots, (n, j)$$$ для некоторого $$$j$$$), главная диагональ (ячейки $$$(1, 1), (2, 2), \ldots, (n, n)$$$) и побочная диагональ (ячейки $$$(1, n), (2, n - 1), \ldots, (n, 1)$$$).</p><p>Определите вероятность того, что ваша табличка окажется выигрышной, и выведите её по модулю $$$31\,607$$$ (см. формат вывода).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$2 \le n \le 21$$$) — длина стороны таблички.</p><p>В $$$i$$$-й из следующих $$$n$$$ строк задано $$$n$$$ целых чисел $$$a_{i, 1}, a_{i, 2}, \ldots, a_{i, n}$$$ ($$$0 &lt; a_{i, j} &lt; 10^4$$$). Вероятность того, что событие в ячейке таблицы $$$(i, j)$$$ произойдёт, равна $$$a_{i, j} \cdot 10^{-4}$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите вероятность того, что табличка окажется выигрышной, по модулю $$$31\,607$$$.</p><p>Формально, пусть $$$M = 31\,607$$$. Можно показать, что ответ может быть представлен в виде несократимой дроби $$$\frac{p}{q}$$$, где $$$p$$$ и $$$q$$$ — целые числа, и $$$q \not \equiv 0 \pmod{M}$$$. Выведите целое число, равное $$$p \cdot q^{-1} \bmod M$$$. Другими словами, выведите такое целое число $$$x$$$, что $$$0 \le x &lt; M$$$ и $$$x \cdot q \equiv p \pmod{M}$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 5000 5000 5000 5000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5927 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2500 6000 3000 4000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 24812 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1000 2000 3000 4000 5000 6000 7000 8000 9000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 25267 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере любые два события образуют линию, поэтому табличка будет выигрышной, если произойдут любые два события. Вероятность этого равна $$$\frac{11}{16}$$$, а $$$5927 \cdot 16 \equiv 11 \pmod{31\,607}$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="ddd87a6f9215c8138c8c6297d0137bfe"/> <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="3656e17289c8c70050c1f01fdb01de047e253b00"/> <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='ddd87a6f9215c8138c8c6297d0137bfe'>&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="position:relative;bottom:4px;"><a href="/vkcup2021"><img src="https://assets.codeforces.com/images/vkcup21-500x70-1.jpg"/></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%2F1544%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='ddd87a6f9215c8138c8c6297d0137bfe'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1544">VK Cup 2021 - Отборочный раунд (Engine)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </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/1544/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Вероятности, мат. ожидания, случайные величины и др."> теория вероятностей </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *2600 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ddd87a6f9215c8138c8c6297d0137bfe'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1049165"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ddd87a6f9215c8138c8c6297d0137bfe'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1049165"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92916" title="VK Cup 2021 — Отбор (Engine) и Codeforces Round #733 (Div. 1 + Div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14034:14035" 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/92951" title="Codeforces Round #733 Editorial (all problems)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14040" resourceName="Codeforces Round #733 Editorial (all problems)" resourceManual="true" src="//codeforces.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/1544">Задачи</a></li> <li><a href="/contest/1544/submit">Отослать</a></li> <li><a href="/contest/1544/my">Мои посылки</a></li> <li><a href="/contest/1544/status">Статус</a></li> <li><a href="/contest/1544/hacks">Взломы</a></li> <li><a href="/contest/1544/room/1">Комната</a></li> <li><a href="/contest/1544/standings">Положение</a></li> <li><a href="/contest/1544/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2183df564f8b5865473e9d87626f93e82f122eab"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>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>В предвкушении VK Fest 2021 вы составили себе табличку из $$$n$$$ строк и $$$n$$$ столбцов, и в каждую ячейку этой таблички записали некоторое событие, связанное с фестивалем, которое может произойти или нет — например, удастся ли вам выиграть на фестивале приз, или пойдёт ли дождь.</p><p>Алгоритмы предсказания ВКонтакте уже оценили для каждого события вероятность того, что оно произойдёт. Событие в строке $$$i$$$ и столбце $$$j$$$ произойдёт с вероятностью $$$a_{i, j} \cdot 10^{-4}$$$. При этом все события совместно независимы друг от друга.</p><p>Назовём табличку с событиями <span class="tex-font-style-it">выигрышной</span>, если найдётся такая линия, на которой произойдут все $$$n$$$ событий. Линией считается любая горизонталь (ячейки $$$(i, 1), (i, 2), \ldots, (i, n)$$$ для некоторого $$$i$$$), любая вертикаль (ячейки $$$(1, j), (2, j), \ldots, (n, j)$$$ для некоторого $$$j$$$), главная диагональ (ячейки $$$(1, 1), (2, 2), \ldots, (n, n)$$$) и побочная диагональ (ячейки $$$(1, n), (2, n - 1), \ldots, (n, 1)$$$).</p><p>Определите вероятность того, что ваша табличка окажется выигрышной, и выведите её по модулю $$$31\,607$$$ (см. формат вывода).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$n$$$ ($$$2 \le n \le 21$$$) — длина стороны таблички.</p><p>В $$$i$$$-й из следующих $$$n$$$ строк задано $$$n$$$ целых чисел $$$a_{i, 1}, a_{i, 2}, \ldots, a_{i, n}$$$ ($$$0 &lt; a_{i, j} &lt; 10^4$$$). Вероятность того, что событие в ячейке таблицы $$$(i, j)$$$ произойдёт, равна $$$a_{i, j} \cdot 10^{-4}$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите вероятность того, что табличка окажется выигрышной, по модулю $$$31\,607$$$.</p><p>Формально, пусть $$$M = 31\,607$$$. Можно показать, что ответ может быть представлен в виде несократимой дроби $$$\frac{p}{q}$$$, где $$$p$$$ и $$$q$$$ — целые числа, и $$$q \not \equiv 0 \pmod{M}$$$. Выведите целое число, равное $$$p \cdot q^{-1} \bmod M$$$. Другими словами, выведите такое целое число $$$x$$$, что $$$0 \le x &lt; M$$$ и $$$x \cdot q \equiv p \pmod{M}$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 5000 5000 5000 5000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5927 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2500 6000 3000 4000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 24812 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1000 2000 3000 4000 5000 6000 7000 8000 9000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 25267 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере любые два события образуют линию, поэтому табличка будет выигрышной, если произойдут любые два события. Вероятность этого равна $$$\frac{11}{16}$$$, а $$$5927 \cdot 16 \equiv 11 \pmod{31\,607}$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c7b678e89da5',t:'MTY5NjY2NzQwNS44OTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0412\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0438, \u043c\u0430\u0442. \u043e\u0436\u0438\u0434\u0430\u043d\u0438\u044f, \u0441\u043b\u0443\u0447\u0430\u0439\u043d\u044b\u0435 \u0432\u0435\u043b\u0438\u0447\u0438\u043d\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\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", "*2600"]
1544G
1544
G
ru
G. Вот это переворот
<div class="problem-statement"><div class="header"><div class="title">G. Вот это переворот</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть две строки $$$a$$$ и $$$b$$$ равной длины $$$n$$$, состоящие из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>, а также целое число $$$k$$$.</p><p>Вам нужно сделать строки $$$a$$$ и $$$b$$$ равными.</p><p>За один шаг вы можете выбрать любую подстроку $$$a$$$, содержащую ровно $$$k$$$ символов <span class="tex-font-style-tt">1</span> (и произвольное число символов <span class="tex-font-style-tt">0</span>), и перевернуть её. Формально, если $$$a = a_1 a_2 \ldots a_n$$$, вы можете выбрать любые $$$l$$$ и $$$r$$$ ($$$1 \le l \le r \le n$$$) такие, что среди символов $$$a_l, a_{l+1}, \ldots, a_r$$$ ровно $$$k$$$ единиц, и сделать $$$a$$$ равной $$$a_1 a_2 \ldots a_{l-1} a_r a_{r-1} \ldots a_l a_{r+1} a_{r+2} \ldots a_n$$$.</p><p>Найдите способ сделать строки $$$a$$$ и $$$b$$$ равными, используя не более $$$4n$$$ переворотов такого рода, или определите, что такого способа не существует. Минимизировать число переворотов не нужно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Во входных данных находятся несколько наборов входных данных. В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 2000$$$) — количество наборов входных данных. Далее следуют наборы входных данных.</p><p>Каждый набор входных данных состоит из трёх строк. Первая строка содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 2000$$$; $$$0 \le k \le n$$$).</p><p>Вторая строка содержит строку $$$a$$$ длины $$$n$$$.</p><p>Третья строка содержит строку $$$b$$$ той же длины. Обе строки состоят из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$2000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, если невозможно сделать $$$a$$$ и $$$b$$$ равными, используя не более $$$4n$$$ переворотов, выведите одно целое число $$$-1$$$.</p><p>В противном случае выведите целое число $$$m$$$ ($$$0 \le m \le 4n$$$) — число переворотов в вашей последовательности шагов, и $$$m$$$ пар целых чисел $$$l_i, r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — границы подстрок $$$a$$$, которые нужно перевернуть, в хронологическом порядке. Каждая подстрока должна содержать ровно $$$k$$$ единиц на момент переворота.</p><p>Обратите внимание, что $$$m$$$ минимизировать не нужно. Если существует несколько решений, выведите любое из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 6 1 101010 010101 6 3 101010 010101 6 0 101010 010101 6 6 101010 010101 4 2 0000 1111 9 2 011100101 101001011 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 2 3 4 5 6 1 1 6 -1 -1 -1 5 4 8 8 9 3 6 1 4 3 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных после первого переворота $$$a = $$$ <span class="tex-font-style-tt">011010</span>, после второго переворота $$$a = $$$ <span class="tex-font-style-tt">010110</span>, после третьего переворота $$$a = $$$ <span class="tex-font-style-tt">010101</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="b51ed379cd4239303672653372c8e942"/> <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="3656e17289c8c70050c1f01fdb01de047e253b00"/> <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='b51ed379cd4239303672653372c8e942'>&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="position:relative;bottom:4px;"><a href="/vkcup2021"><img src="https://assets.codeforces.com/images/vkcup21-500x70-1.jpg"/></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%2F1544%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='b51ed379cd4239303672653372c8e942'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1544">VK Cup 2021 - Отборочный раунд (Engine)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </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/1544/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='b51ed379cd4239303672653372c8e942'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1049166"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b51ed379cd4239303672653372c8e942'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1049166"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92916" title="VK Cup 2021 — Отбор (Engine) и Codeforces Round #733 (Div. 1 + Div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14034:14035" 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/92951" title="Codeforces Round #733 Editorial (all problems)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14040" resourceName="Codeforces Round #733 Editorial (all problems)" resourceManual="true" src="//codeforces.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/1544">Задачи</a></li> <li><a href="/contest/1544/submit">Отослать</a></li> <li><a href="/contest/1544/my">Мои посылки</a></li> <li><a href="/contest/1544/status">Статус</a></li> <li><a href="/contest/1544/hacks">Взломы</a></li> <li><a href="/contest/1544/room/1">Комната</a></li> <li><a href="/contest/1544/standings">Положение</a></li> <li><a href="/contest/1544/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_a8bd1126058c399675da0c763c4838dd03a73c7f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">G. Вот это переворот</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть две строки $$$a$$$ и $$$b$$$ равной длины $$$n$$$, состоящие из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>, а также целое число $$$k$$$.</p><p>Вам нужно сделать строки $$$a$$$ и $$$b$$$ равными.</p><p>За один шаг вы можете выбрать любую подстроку $$$a$$$, содержащую ровно $$$k$$$ символов <span class="tex-font-style-tt">1</span> (и произвольное число символов <span class="tex-font-style-tt">0</span>), и перевернуть её. Формально, если $$$a = a_1 a_2 \ldots a_n$$$, вы можете выбрать любые $$$l$$$ и $$$r$$$ ($$$1 \le l \le r \le n$$$) такие, что среди символов $$$a_l, a_{l+1}, \ldots, a_r$$$ ровно $$$k$$$ единиц, и сделать $$$a$$$ равной $$$a_1 a_2 \ldots a_{l-1} a_r a_{r-1} \ldots a_l a_{r+1} a_{r+2} \ldots a_n$$$.</p><p>Найдите способ сделать строки $$$a$$$ и $$$b$$$ равными, используя не более $$$4n$$$ переворотов такого рода, или определите, что такого способа не существует. Минимизировать число переворотов не нужно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Во входных данных находятся несколько наборов входных данных. В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 2000$$$) — количество наборов входных данных. Далее следуют наборы входных данных.</p><p>Каждый набор входных данных состоит из трёх строк. Первая строка содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 2000$$$; $$$0 \le k \le n$$$).</p><p>Вторая строка содержит строку $$$a$$$ длины $$$n$$$.</p><p>Третья строка содержит строку $$$b$$$ той же длины. Обе строки состоят из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$2000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, если невозможно сделать $$$a$$$ и $$$b$$$ равными, используя не более $$$4n$$$ переворотов, выведите одно целое число $$$-1$$$.</p><p>В противном случае выведите целое число $$$m$$$ ($$$0 \le m \le 4n$$$) — число переворотов в вашей последовательности шагов, и $$$m$$$ пар целых чисел $$$l_i, r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — границы подстрок $$$a$$$, которые нужно перевернуть, в хронологическом порядке. Каждая подстрока должна содержать ровно $$$k$$$ единиц на момент переворота.</p><p>Обратите внимание, что $$$m$$$ минимизировать не нужно. Если существует несколько решений, выведите любое из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 6 1 101010 010101 6 3 101010 010101 6 0 101010 010101 6 6 101010 010101 4 2 0000 1111 9 2 011100101 101001011 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 2 3 4 5 6 1 1 6 -1 -1 -1 5 4 8 8 9 3 6 1 4 3 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных после первого переворота $$$a = $$$ <span class="tex-font-style-tt">011010</span>, после второго переворота $$$a = $$$ <span class="tex-font-style-tt">010110</span>, после третьего переворота $$$a = $$$ <span class="tex-font-style-tt">010101</span>.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=G]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c7be7d421660',t:'MTY5NjY2NzQwNy4xNTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*3300"]
1544H
1544
H
ru
H. Премия Тьюринга
<div class="problem-statement"><div class="header"><div class="title">H. Премия Тьюринга</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>10 секунд</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>Ячейки пронумерованы слева направо подряд идущими целыми числами, а Алан изначально стоит в ячейке $$$0$$$. Слева от любой ячейки $$$x$$$ находится ячейка $$$x - 1$$$, а справа — ячейка $$$x + 1$$$.</p><p>Каждая ячейка может либо содержать целое число, либо быть пустой. Изначально все ячейки пусты.</p><p>Алану выдали перестановку $$$a_1, a_2, \ldots, a_n$$$ чисел от $$$1$$$ до $$$n$$$, выбранную <span class="tex-font-style-bf">случайно равновероятно</span> среди всех перестановок длины $$$n$$$.</p><p>В момент времени $$$1$$$ в ячейку $$$0$$$, в которой находится Алан, записывается число $$$a_1$$$.</p><p>В каждый момент времени $$$i$$$ до $$$2$$$ до $$$n$$$ включительно происходит следующее. Сначала Алан принимает решение, остаться ли ему в той же ячейке, где он сейчас находится, сдвинуться на соседнюю ячейку слева, или же сдвинуться на соседнюю ячейку справа. После этого в ту ячейку, где находится Алан, записывается число $$$a_i$$$. Если ячейка уже содержала некоторое число, старое число перезаписывается и больше не играет роли.</p><p>После того, как в момент времени $$$n$$$ в некоторую ячейку будет записано число $$$a_n$$$, сформируется последовательность $$$b$$$ из всех чисел, записанных в ячейках, слева направо. Пустые ячейки игнорируются.</p><p>Премия Тьюринга будет равна длине наибольшей возрастающей подпоследовательности последовательности $$$b$$$.</p><p>Помогите Алану и определите, каков максимальный возможный размер его премии, если он будет действовать оптимально.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Во входных данных находятся несколько наборов входных данных. В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных. Далее следуют наборы входных данных.</p><p>Каждый набор входных данных задан на двух строках. Первая строка набора входных данных содержит целое число $$$n$$$ ($$$2 \le n \le 15\,000$$$) — длину перестановки, предоставленной Алану.</p><p>Вторая строка содержит $$$n$$$ различных целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — элементы перестановки.</p><p>Гарантируется, что перестановка была выбрана случайно равновероятно среди всех перестановок соответствующей длины.</p><p>Сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$15\,000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — максимальный возможный размер премии Тьюринга.</p><p><span class="tex-font-style-bf">Взломы в этой задаче запрещены.</span></p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 2 1 2 4 4 1 2 3 7 3 6 5 7 4 1 2 7 5 2 3 7 6 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 4 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p><span class="tex-font-style-it">Наибольшая возрастающая подпоследовательность</span> последовательности $$$b$$$ — это самая длинная возрастающая последовательность, которую можно получить удалением нескольких (возможно, ни одного или всех) элементов из $$$b$$$.</p><p>В первом наборе входных данных Алан может принять решение только в момент времени $$$2$$$. Если Алан останется в ячейке $$$0$$$, последовательность $$$b$$$ будет равна $$$[2]$$$. Если Алан сдвинется влево, в ячейку $$$-1$$$, последовательность $$$b$$$ будет равна $$$[2, 1]$$$. Если Алан сдвинется вправо, в ячейку $$$1$$$, последовательность $$$b$$$ будет равна $$$[1, 2]$$$. Только в последнем случае длина наибольшей возрастающей подпоследовательности в $$$b$$$ равна $$$2$$$, следовательно, ответ равен $$$2$$$.</p><p>Во втором наборе входных данных одна из оптимальных последовательностей действий такова: сдвинуться влево в моменты времени $$$2$$$ и $$$3$$$, и сдвинуться вправо в момент времени $$$4$$$. Тогда последовательность $$$b$$$ будет равна $$$[2, 3, 4]$$$, длина её наибольшей возрастающей подпоследовательности — $$$3$$$.</p><p>В третьем наборе входных данных один из оптимальных способов — всё время сдвигаться влево. Тогда последовательность $$$b$$$ будет равна $$$[2, 1, 4, 7, 5, 6, 3]$$$, длина её наибольшей возрастающей подпоследовательности — $$$4$$$.</p><p>В четвёртом наборе входных данных один из оптимальных способов — четырежды сдвинуться вправо, далее один раз сдвинуться влево, и один раз остаться на месте. Последовательность $$$b$$$ будет равна $$$[5, 2, 3, 4, 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="9646ed689bf244b5c7c26f0a27009cfa"/> <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="3656e17289c8c70050c1f01fdb01de047e253b00"/> <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='9646ed689bf244b5c7c26f0a27009cfa'>&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="position:relative;bottom:4px;"><a href="/vkcup2021"><img src="https://assets.codeforces.com/images/vkcup21-500x70-1.jpg"/></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%2F1544%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='9646ed689bf244b5c7c26f0a27009cfa'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1544">VK Cup 2021 - Отборочный раунд (Engine)</a></th> </tr> <tr> <td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td> </tr> </tbody> </table> </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/1544/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='9646ed689bf244b5c7c26f0a27009cfa'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1049167"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='9646ed689bf244b5c7c26f0a27009cfa'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1049167"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92916" title="VK Cup 2021 — Отбор (Engine) и Codeforces Round #733 (Div. 1 + Div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14034:14035" 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/92951" title="Codeforces Round #733 Editorial (all problems)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14040" resourceName="Codeforces Round #733 Editorial (all problems)" resourceManual="true" src="//codeforces.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/1544">Задачи</a></li> <li><a href="/contest/1544/submit">Отослать</a></li> <li><a href="/contest/1544/my">Мои посылки</a></li> <li><a href="/contest/1544/status">Статус</a></li> <li><a href="/contest/1544/hacks">Взломы</a></li> <li><a href="/contest/1544/room/1">Комната</a></li> <li><a href="/contest/1544/standings">Положение</a></li> <li><a href="/contest/1544/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_056b2652d299f51f10090c645331539965fe68a8"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>10 секунд</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>Ячейки пронумерованы слева направо подряд идущими целыми числами, а Алан изначально стоит в ячейке $$$0$$$. Слева от любой ячейки $$$x$$$ находится ячейка $$$x - 1$$$, а справа — ячейка $$$x + 1$$$.</p><p>Каждая ячейка может либо содержать целое число, либо быть пустой. Изначально все ячейки пусты.</p><p>Алану выдали перестановку $$$a_1, a_2, \ldots, a_n$$$ чисел от $$$1$$$ до $$$n$$$, выбранную <span class="tex-font-style-bf">случайно равновероятно</span> среди всех перестановок длины $$$n$$$.</p><p>В момент времени $$$1$$$ в ячейку $$$0$$$, в которой находится Алан, записывается число $$$a_1$$$.</p><p>В каждый момент времени $$$i$$$ до $$$2$$$ до $$$n$$$ включительно происходит следующее. Сначала Алан принимает решение, остаться ли ему в той же ячейке, где он сейчас находится, сдвинуться на соседнюю ячейку слева, или же сдвинуться на соседнюю ячейку справа. После этого в ту ячейку, где находится Алан, записывается число $$$a_i$$$. Если ячейка уже содержала некоторое число, старое число перезаписывается и больше не играет роли.</p><p>После того, как в момент времени $$$n$$$ в некоторую ячейку будет записано число $$$a_n$$$, сформируется последовательность $$$b$$$ из всех чисел, записанных в ячейках, слева направо. Пустые ячейки игнорируются.</p><p>Премия Тьюринга будет равна длине наибольшей возрастающей подпоследовательности последовательности $$$b$$$.</p><p>Помогите Алану и определите, каков максимальный возможный размер его премии, если он будет действовать оптимально.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Во входных данных находятся несколько наборов входных данных. В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных. Далее следуют наборы входных данных.</p><p>Каждый набор входных данных задан на двух строках. Первая строка набора входных данных содержит целое число $$$n$$$ ($$$2 \le n \le 15\,000$$$) — длину перестановки, предоставленной Алану.</p><p>Вторая строка содержит $$$n$$$ различных целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — элементы перестановки.</p><p>Гарантируется, что перестановка была выбрана случайно равновероятно среди всех перестановок соответствующей длины.</p><p>Сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$15\,000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — максимальный возможный размер премии Тьюринга.</p><p><span class="tex-font-style-bf">Взломы в этой задаче запрещены.</span></p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 2 1 2 4 4 1 2 3 7 3 6 5 7 4 1 2 7 5 2 3 7 6 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 4 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p><span class="tex-font-style-it">Наибольшая возрастающая подпоследовательность</span> последовательности $$$b$$$ — это самая длинная возрастающая последовательность, которую можно получить удалением нескольких (возможно, ни одного или всех) элементов из $$$b$$$.</p><p>В первом наборе входных данных Алан может принять решение только в момент времени $$$2$$$. Если Алан останется в ячейке $$$0$$$, последовательность $$$b$$$ будет равна $$$[2]$$$. Если Алан сдвинется влево, в ячейку $$$-1$$$, последовательность $$$b$$$ будет равна $$$[2, 1]$$$. Если Алан сдвинется вправо, в ячейку $$$1$$$, последовательность $$$b$$$ будет равна $$$[1, 2]$$$. Только в последнем случае длина наибольшей возрастающей подпоследовательности в $$$b$$$ равна $$$2$$$, следовательно, ответ равен $$$2$$$.</p><p>Во втором наборе входных данных одна из оптимальных последовательностей действий такова: сдвинуться влево в моменты времени $$$2$$$ и $$$3$$$, и сдвинуться вправо в момент времени $$$4$$$. Тогда последовательность $$$b$$$ будет равна $$$[2, 3, 4]$$$, длина её наибольшей возрастающей подпоследовательности — $$$3$$$.</p><p>В третьем наборе входных данных один из оптимальных способов — всё время сдвигаться влево. Тогда последовательность $$$b$$$ будет равна $$$[2, 1, 4, 7, 5, 6, 3]$$$, длина её наибольшей возрастающей подпоследовательности — $$$4$$$.</p><p>В четвёртом наборе входных данных один из оптимальных способов — четырежды сдвинуться вправо, далее один раз сдвинуться влево, и один раз остаться на месте. Последовательность $$$b$$$ будет равна $$$[5, 2, 3, 4, 6]$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=H]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c7c65f6e1646',t:'MTY5NjY2NzQwOC40NjEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*3400"]
1545A
1545
A
ru
A. AquaMoon и странная сортировка
<div class="problem-statement"><div class="header"><div class="title">A. AquaMoon и странная сортировка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У AquaMoon есть $$$n$$$ друзей. Они встали в ряд. $$$i$$$-й слева друг надел футболку с числом $$$a_i$$$, написанным на ней. Каждый друг смотрит в одну из двух сторон налево или направо. В начале все друзья смотрят <span class="tex-font-style-bf">направо</span>.</p><p>AquaMoon может делать операции с друзьями. На каждой операции AquaMoon может выбрать два <span class="tex-font-style-bf">соседних</span> в ряду друга и поменять их местами. После каждой операции оба друга изменяют направление, в котором смотрели, на противоположное: если кто-то смотрел налево, он будет смотреть направо, и наоборот.</p><p>AquaMoon надеется, что после нескольких операций числа, написанные на футболках у $$$n$$$ друзей станут <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>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 50$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — количество друзей Aquamoon.</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^5$$$) — числа, записанные на футболках.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">YES</span>» (без кавычек), если существует возможная последовательность операций; иначе, выведите «<span class="tex-font-style-tt">NO</span>» (без кавычек).</p><p>Вы можете выводить каждую букву в любом регистре (строчную или заглавную).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 4 3 2 5 4 3 3 2 2 5 1 2 3 5 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Возможная последовательность операций для первого набора входных данных:</p><ol> <li> Поменять $$$a_1$$$ и $$$a_2$$$. В результате последовательность чисел $$$3, 4, 2, 5$$$. Друзья смотрят: налево, налево, направо, направо. </li><li> Поменять $$$a_2$$$ и $$$a_3$$$. В результате последовательность чисел $$$3, 2, 4, 5$$$. Друзья смотрят: налево, налево, направо, направо. </li><li> Поменять $$$a_1$$$ и $$$a_2$$$. В результате последовательность чисел $$$2, 3, 4, 5$$$. Друзья смотрят: направо, направо, направо, направо. </li></ol></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="9e124862bd506c7717a804f38d7c6def"/> <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="3fe66514c760cbfa0a037863c569968d78f9afa9"/> <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='9e124862bd506c7717a804f38d7c6def'>&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%2F1545%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='9e124862bd506c7717a804f38d7c6def'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1545">Codeforces Round 732 (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='9e124862bd506c7717a804f38d7c6def'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1545/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='9e124862bd506c7717a804f38d7c6def'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1042717"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='9e124862bd506c7717a804f38d7c6def'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1042717"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92482" title="Codeforces Round #732" target="_blank">Codeforces Round #732 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13990" resourceName="Codeforces Round #732" resourceManual="true" src="//codeforces.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/92739" title="Codeforces Round #732 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13996" resourceName="Codeforces Round #732 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/1545">Задачи</a></li> <li><a href="/contest/1545/submit">Отослать</a></li> <li><a href="/contest/1545/my">Мои посылки</a></li> <li><a href="/contest/1545/status">Статус</a></li> <li><a href="/contest/1545/hacks">Взломы</a></li> <li><a href="/contest/1545/room/1">Комната</a></li> <li><a href="/contest/1545/standings">Положение</a></li> <li><a href="/contest/1545/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9e8031890e04fbb3bc643879e3f5b41629f344cc"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. AquaMoon и странная сортировка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У AquaMoon есть $$$n$$$ друзей. Они встали в ряд. $$$i$$$-й слева друг надел футболку с числом $$$a_i$$$, написанным на ней. Каждый друг смотрит в одну из двух сторон налево или направо. В начале все друзья смотрят <span class="tex-font-style-bf">направо</span>.</p><p>AquaMoon может делать операции с друзьями. На каждой операции AquaMoon может выбрать два <span class="tex-font-style-bf">соседних</span> в ряду друга и поменять их местами. После каждой операции оба друга изменяют направление, в котором смотрели, на противоположное: если кто-то смотрел налево, он будет смотреть направо, и наоборот.</p><p>AquaMoon надеется, что после нескольких операций числа, написанные на футболках у $$$n$$$ друзей станут <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>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 50$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — количество друзей Aquamoon.</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^5$$$) — числа, записанные на футболках.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">YES</span>» (без кавычек), если существует возможная последовательность операций; иначе, выведите «<span class="tex-font-style-tt">NO</span>» (без кавычек).</p><p>Вы можете выводить каждую букву в любом регистре (строчную или заглавную).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 4 3 2 5 4 3 3 2 2 5 1 2 3 5 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Возможная последовательность операций для первого набора входных данных:</p><ol> <li> Поменять $$$a_1$$$ и $$$a_2$$$. В результате последовательность чисел $$$3, 4, 2, 5$$$. Друзья смотрят: налево, налево, направо, направо. </li><li> Поменять $$$a_2$$$ и $$$a_3$$$. В результате последовательность чисел $$$3, 2, 4, 5$$$. Друзья смотрят: налево, налево, направо, направо. </li><li> Поменять $$$a_1$$$ и $$$a_2$$$. В результате последовательность чисел $$$2, 3, 4, 5$$$. Друзья смотрят: направо, направо, направо, направо. </li></ol></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c7ce8a271625',t:'MTY5NjY2NzQwOS45MTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\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"]
["\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1500"]
1545B
1545
B
ru
B. AquaMoon и шахматы
<div class="problem-statement"><div class="header"><div class="title">B. AquaMoon и шахматы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Cirno дала AquaMoon шахматную доску размера $$$1 \times n$$$. Ее клетки пронумерованы целыми числами от $$$1$$$ до $$$n$$$ слева направо. Изначально в некоторых клетках находится одна пешка, а остальные клетки свободны.</p><p>На каждой операции AquaMoon может выбрать клетку $$$i$$$ с пешкой и сделать <span class="tex-font-style-bf">любую</span> из следующих операций (если возможно): </p><ul> <li> Переместить пешку из нее в клетку $$$(i+2)$$$, если $$$i+2 \leq n$$$, $$$(i+1)$$$-я клетка занята пешкой, а $$$(i+2)$$$-я клетка свободна. </li><li> Переместить пешку из нее в клетку $$$(i-2)$$$, если $$$i-2 \geq 1$$$, $$$(i-1)$$$-я клетка занята пешкой, а $$$(i-2)$$$-я клетка свободна. </li></ul><p>Дано изначальное состояние шахматной доски. AquaMoon хочет посчитать количество состояний, которые достижимы из начального состояния с помощью некоторой последовательности операций. Но она не очень хороша в программировании. Можете ли вы помочь ей? Поскольку ответ может быть большим, найдите его по модулю $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — размер шахматной доски.</p><p>Во второй строке находится строка, состоящая из $$$n$$$ символов «<span class="tex-font-style-tt">0</span>» или «<span class="tex-font-style-tt">1</span>». Если $$$i$$$-й символ это «<span class="tex-font-style-tt">1</span>», $$$i$$$-я клетка изначальна занята пешкой, иначе $$$i$$$-я клетка изначально свободна.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите количество состояний, которое может быть получено из начального с помощью некоторой последовательности операций по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 6 1 1287 1287 715 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных строки «<span class="tex-font-style-tt">1100</span>», «<span class="tex-font-style-tt">0110</span>» и «<span class="tex-font-style-tt">0011</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="305e33c4f376e94b354f367a4cd23588"/> <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="3fe66514c760cbfa0a037863c569968d78f9afa9"/> <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='305e33c4f376e94b354f367a4cd23588'>&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%2F1545%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='305e33c4f376e94b354f367a4cd23588'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1545">Codeforces Round 732 (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='305e33c4f376e94b354f367a4cd23588'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1545/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='305e33c4f376e94b354f367a4cd23588'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1042718"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='305e33c4f376e94b354f367a4cd23588'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1042718"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92482" title="Codeforces Round #732" target="_blank">Codeforces Round #732 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13990" resourceName="Codeforces Round #732" resourceManual="true" src="//codeforces.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/92739" title="Codeforces Round #732 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13996" resourceName="Codeforces Round #732 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/1545">Задачи</a></li> <li><a href="/contest/1545/submit">Отослать</a></li> <li><a href="/contest/1545/my">Мои посылки</a></li> <li><a href="/contest/1545/status">Статус</a></li> <li><a href="/contest/1545/hacks">Взломы</a></li> <li><a href="/contest/1545/room/1">Комната</a></li> <li><a href="/contest/1545/standings">Положение</a></li> <li><a href="/contest/1545/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_96059d2d23427a8c26a22b4280bb4b0e99286115"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. AquaMoon и шахматы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Cirno дала AquaMoon шахматную доску размера $$$1 \times n$$$. Ее клетки пронумерованы целыми числами от $$$1$$$ до $$$n$$$ слева направо. Изначально в некоторых клетках находится одна пешка, а остальные клетки свободны.</p><p>На каждой операции AquaMoon может выбрать клетку $$$i$$$ с пешкой и сделать <span class="tex-font-style-bf">любую</span> из следующих операций (если возможно): </p><ul> <li> Переместить пешку из нее в клетку $$$(i+2)$$$, если $$$i+2 \leq n$$$, $$$(i+1)$$$-я клетка занята пешкой, а $$$(i+2)$$$-я клетка свободна. </li><li> Переместить пешку из нее в клетку $$$(i-2)$$$, если $$$i-2 \geq 1$$$, $$$(i-1)$$$-я клетка занята пешкой, а $$$(i-2)$$$-я клетка свободна. </li></ul><p>Дано изначальное состояние шахматной доски. AquaMoon хочет посчитать количество состояний, которые достижимы из начального состояния с помощью некоторой последовательности операций. Но она не очень хороша в программировании. Можете ли вы помочь ей? Поскольку ответ может быть большим, найдите его по модулю $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — размер шахматной доски.</p><p>Во второй строке находится строка, состоящая из $$$n$$$ символов «<span class="tex-font-style-tt">0</span>» или «<span class="tex-font-style-tt">1</span>». Если $$$i$$$-й символ это «<span class="tex-font-style-tt">1</span>», $$$i$$$-я клетка изначальна занята пешкой, иначе $$$i$$$-я клетка изначально свободна.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите количество состояний, которое может быть получено из начального с помощью некоторой последовательности операций по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 6 1 1287 1287 715 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных строки «<span class="tex-font-style-tt">1100</span>», «<span class="tex-font-style-tt">0110</span>» и «<span class="tex-font-style-tt">0011</span>» могут быть получены из изначального состояния с помощью некоторой последовательности операций.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30:11</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c7d99ab70004',t:'MTY5NjY2NzQxMS41MjEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1900"]
1545C
1545
C
ru
C. AquaMoon и перестановки
<div class="problem-statement"><div class="header"><div class="title">C. AquaMoon и перестановки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Cirno подготовила $$$n$$$ массивов длины $$$n$$$ каждый. Каждый массив — это перестановка из $$$n$$$ целых чисел от $$$1$$$ до $$$n$$$. Эти массивы специальные: для всех $$$1 \leq i \leq n$$$, если мы возьмем $$$i$$$-й элемент каждого массива и построим другой массив длины $$$n$$$, состоящий из этих элементов, получившийся массив также будет перестановкой $$$n$$$ чисел от $$$1$$$ до $$$n$$$. Другими словами, если эти $$$n$$$ массивов расположить друг под другом, образовав матрицу с $$$n$$$ строками и $$$n$$$ столбцами, эта матрица будет <a href="https://ru.wikipedia.org/wiki/Латинский_квадрат">латинским квадратом</a>.</p><p>После этого Cirno добавила дополнительные $$$n$$$ массивов, каждый массив также является перестановкой из $$$n$$$ целых чисел от $$$1$$$ до $$$n$$$. Для всех $$$1 \leq i \leq n$$$ существует <span class="tex-font-style-bf">хотя бы одна</span> позиция $$$1 \leq k \leq n$$$, такая что для $$$i$$$-го и $$$(n + i)$$$-го массивов $$$k$$$-е элементы совпадают. Обратите внимание, что массивы с индексами от $$$n + 1$$$ до $$$2n$$$ <span class="tex-font-style-bf">не обязаны</span> образовывать латинский квадрат.</p><p>Также Cirno убедилась, что среди $$$2n$$$ массивов никакие два не равны, то есть для всех пар индексов $$$1 \leq i &lt; j \leq 2n$$$ существует <span class="tex-font-style-bf">хотя бы одна</span> позиция $$$1 \leq k \leq n$$$, такая что в $$$i$$$-м и $$$j$$$-м массивах $$$k$$$-е элементы <span class="tex-font-style-bf">различны</span>.</p><p>В конце Cirno произвольно поменяла порядок, в котором расположены подготовленные $$$2n$$$ массивов.</p><p>AquaMoon называет подмножество всех $$$2n$$$ массивов размера $$$n$$$ <span class="tex-font-style-bf">хорошим</span>, если эти массивы образуют латинский квадрат.</p><p>AquaMoon хочет узнать, сколько хороших подмножеств существует. Поскольку это количество может быть очень большим, найдите его по модулю $$$998\,244\,353$$$. Также она хочет найти любое хорошее подмножество. Можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$5 \leq n \leq 500$$$).</p><p>Затем $$$2n$$$ строк следует. $$$i$$$-я из этих строк содержит $$$n$$$ целых чисел, составляющих $$$i$$$-й массив.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$500$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите две строки.</p><p>В первой строке выведите количество хороших подмножеств по модулю $$$998\,244\,353$$$.</p><p>Во второй строке выведите $$$n$$$ индексов от $$$1$$$ до $$$2n$$$ — индексы $$$n$$$ массивов, которые образуют хорошее подмножество (вы можете вывести их в любом порядке). Если существует несколько возможных ответов — выведите любой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 7 1 2 3 4 5 6 7 2 3 4 5 6 7 1 3 4 5 6 7 1 2 4 5 6 7 1 2 3 5 6 7 1 2 3 4 6 7 1 2 3 4 5 7 1 2 3 4 5 6 1 2 3 4 5 7 6 1 3 4 5 6 7 2 1 4 5 6 7 3 2 1 5 6 7 4 2 3 1 6 7 5 2 3 4 1 7 6 2 3 4 5 1 7 2 3 4 5 6 5 4 5 1 2 3 3 5 2 4 1 1 2 3 4 5 5 2 4 1 3 3 4 5 1 2 2 3 4 5 1 1 3 5 2 4 4 1 3 5 2 2 4 1 3 5 5 1 2 3 4 6 2 3 4 5 6 1 3 1 2 6 4 5 6 1 2 3 4 5 5 6 1 3 2 4 4 3 6 5 2 1 5 6 1 2 3 4 4 5 6 1 2 3 3 4 5 6 1 2 1 2 3 4 5 6 2 5 4 1 6 3 3 2 5 4 1 6 1 4 3 6 5 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 2 3 4 5 6 7 2 1 3 5 6 10 4 1 3 6 7 8 9 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных количество хороших подмножеств равно $$$1$$$. Единственное такое подмножество это подмножество массивов с индексами $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, $$$6$$$, $$$7$$$.</p><p>Во втором наборе входных данных количество хороших подмножеств равно $$$2$$$. Эти подмножества это $$$1$$$, $$$3$$$, $$$5$$$, $$$6$$$, $$$10$$$, а также $$$2$$$, $$$4$$$, $$$7$$$, $$$8$$$, $$$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="22fdd0f3edfb1f3b677215cb730285d0"/> <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="3fe66514c760cbfa0a037863c569968d78f9afa9"/> <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='22fdd0f3edfb1f3b677215cb730285d0'>&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%2F1545%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='22fdd0f3edfb1f3b677215cb730285d0'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1545">Codeforces Round 732 (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='22fdd0f3edfb1f3b677215cb730285d0'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1545/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="2-SAT (2-satisfiability)"> 2-sat </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы"> конструктив </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Паросочетания, теорема Кёнига, вершинные и реберные покрытия в двудольных графах"> паросочетания </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *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='22fdd0f3edfb1f3b677215cb730285d0'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1042719"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='22fdd0f3edfb1f3b677215cb730285d0'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1042719"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92482" title="Codeforces Round #732" target="_blank">Codeforces Round #732 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13990" resourceName="Codeforces Round #732" resourceManual="true" src="//codeforces.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/92739" title="Codeforces Round #732 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13996" resourceName="Codeforces Round #732 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/1545">Задачи</a></li> <li><a href="/contest/1545/submit">Отослать</a></li> <li><a href="/contest/1545/my">Мои посылки</a></li> <li><a href="/contest/1545/status">Статус</a></li> <li><a href="/contest/1545/hacks">Взломы</a></li> <li><a href="/contest/1545/room/1">Комната</a></li> <li><a href="/contest/1545/standings">Положение</a></li> <li><a href="/contest/1545/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d813e315e405cd29035cb2f1e68ad68ed3f45a70"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. AquaMoon и перестановки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Cirno подготовила $$$n$$$ массивов длины $$$n$$$ каждый. Каждый массив — это перестановка из $$$n$$$ целых чисел от $$$1$$$ до $$$n$$$. Эти массивы специальные: для всех $$$1 \leq i \leq n$$$, если мы возьмем $$$i$$$-й элемент каждого массива и построим другой массив длины $$$n$$$, состоящий из этих элементов, получившийся массив также будет перестановкой $$$n$$$ чисел от $$$1$$$ до $$$n$$$. Другими словами, если эти $$$n$$$ массивов расположить друг под другом, образовав матрицу с $$$n$$$ строками и $$$n$$$ столбцами, эта матрица будет <a href="https://ru.wikipedia.org/wiki/Латинский_квадрат">латинским квадратом</a>.</p><p>После этого Cirno добавила дополнительные $$$n$$$ массивов, каждый массив также является перестановкой из $$$n$$$ целых чисел от $$$1$$$ до $$$n$$$. Для всех $$$1 \leq i \leq n$$$ существует <span class="tex-font-style-bf">хотя бы одна</span> позиция $$$1 \leq k \leq n$$$, такая что для $$$i$$$-го и $$$(n + i)$$$-го массивов $$$k$$$-е элементы совпадают. Обратите внимание, что массивы с индексами от $$$n + 1$$$ до $$$2n$$$ <span class="tex-font-style-bf">не обязаны</span> образовывать латинский квадрат.</p><p>Также Cirno убедилась, что среди $$$2n$$$ массивов никакие два не равны, то есть для всех пар индексов $$$1 \leq i &lt; j \leq 2n$$$ существует <span class="tex-font-style-bf">хотя бы одна</span> позиция $$$1 \leq k \leq n$$$, такая что в $$$i$$$-м и $$$j$$$-м массивах $$$k$$$-е элементы <span class="tex-font-style-bf">различны</span>.</p><p>В конце Cirno произвольно поменяла порядок, в котором расположены подготовленные $$$2n$$$ массивов.</p><p>AquaMoon называет подмножество всех $$$2n$$$ массивов размера $$$n$$$ <span class="tex-font-style-bf">хорошим</span>, если эти массивы образуют латинский квадрат.</p><p>AquaMoon хочет узнать, сколько хороших подмножеств существует. Поскольку это количество может быть очень большим, найдите его по модулю $$$998\,244\,353$$$. Также она хочет найти любое хорошее подмножество. Можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$5 \leq n \leq 500$$$).</p><p>Затем $$$2n$$$ строк следует. $$$i$$$-я из этих строк содержит $$$n$$$ целых чисел, составляющих $$$i$$$-й массив.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$500$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите две строки.</p><p>В первой строке выведите количество хороших подмножеств по модулю $$$998\,244\,353$$$.</p><p>Во второй строке выведите $$$n$$$ индексов от $$$1$$$ до $$$2n$$$ — индексы $$$n$$$ массивов, которые образуют хорошее подмножество (вы можете вывести их в любом порядке). Если существует несколько возможных ответов — выведите любой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 7 1 2 3 4 5 6 7 2 3 4 5 6 7 1 3 4 5 6 7 1 2 4 5 6 7 1 2 3 5 6 7 1 2 3 4 6 7 1 2 3 4 5 7 1 2 3 4 5 6 1 2 3 4 5 7 6 1 3 4 5 6 7 2 1 4 5 6 7 3 2 1 5 6 7 4 2 3 1 6 7 5 2 3 4 1 7 6 2 3 4 5 1 7 2 3 4 5 6 5 4 5 1 2 3 3 5 2 4 1 1 2 3 4 5 5 2 4 1 3 3 4 5 1 2 2 3 4 5 1 1 3 5 2 4 4 1 3 5 2 2 4 1 3 5 5 1 2 3 4 6 2 3 4 5 6 1 3 1 2 6 4 5 6 1 2 3 4 5 5 6 1 3 2 4 4 3 6 5 2 1 5 6 1 2 3 4 4 5 6 1 2 3 3 4 5 6 1 2 1 2 3 4 5 6 2 5 4 1 6 3 3 2 5 4 1 6 1 4 3 6 5 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 2 3 4 5 6 7 2 1 3 5 6 10 4 1 3 6 7 8 9 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных количество хороших подмножеств равно $$$1$$$. Единственное такое подмножество это подмножество массивов с индексами $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, $$$6$$$, $$$7$$$.</p><p>Во втором наборе входных данных количество хороших подмножеств равно $$$2$$$. Эти подмножества это $$$1$$$, $$$3$$$, $$$5$$$, $$$6$$$, $$$10$$$, а также $$$2$$$, $$$4$$$, $$$7$$$, $$$8$$$, $$$9$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c7e1be337b3b',t:'MTY5NjY2NzQxMi44NDkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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)", "\u0413\u0440\u0430\u0444\u044b", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0430\u0440\u043e\u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u044f, \u0442\u0435\u043e\u0440\u0435\u043c\u0430 \u041a\u0451\u043d\u0438\u0433\u0430, \u0432\u0435\u0440\u0448\u0438\u043d\u043d\u044b\u0435 \u0438 \u0440\u0435\u0431\u0435\u0440\u043d\u044b\u0435 \u043f\u043e\u043a\u0440\u044b\u0442\u0438\u044f \u0432 \u0434\u0432\u0443\u0434\u043e\u043b\u044c\u043d\u044b\u0445 \u0433\u0440\u0430\u0444\u0430\u0445", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["2-sat", "\u0433\u0440\u0430\u0444\u044b", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u0430\u0440\u043e\u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u044f", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*2800"]
1545D
1545
D
ru
D. AquaMoon и неправильная координата
<div class="problem-statement"><div class="header"><div class="title">D. AquaMoon и неправильная координата</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Cirno дала AquaMoon задачу. Есть $$$m$$$ человек, пронумерованных целыми числами от $$$0$$$ до $$$m - 1$$$. Они стоят на координатной прямой в точках с положительными целочисленными координатами. Они смотрят в направлении увеличения координат.</p><p>В этот момент все начинают бежать с фиксированной скоростью в направлении увеличения координат. Изначальная координата $$$i$$$-о человека на прямой это $$$x_i$$$, а скорость $$$i$$$-о человека это $$$v_i$$$. Поэтому координата $$$i$$$-о человека в момент времени $$$t$$$ будет $$$x_i + t \cdot v_i$$$.</p><p>Cirno запомнила координаты всех $$$m$$$ человек в $$$k$$$ последовательных целочисленных моментах времени от $$$0$$$ до $$$k - 1$$$. В каждый момент координаты всех $$$m$$$ человек были запомнены в <span class="tex-font-style-bf">произвольном порядке</span>.</p><p>Чтобы сделать задачу более веселой, Cirno изменила одну из координат в момент времени $$$y$$$ ($$$0 &lt; y &lt; k-1$$$) на <span class="tex-font-style-bf">другое</span> целое число.</p><p>AquaMoon хочет найти момент времени $$$y$$$ и изначальную координату $$$p$$$ перед изменением. К сожалению, она совсем не программист. Поэтому она не смогла решить эту задачу. Можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p><span class="tex-font-style-bf">Эта задача сделана как интерактивная. Это означает, что ваше решение будет считывать входные данные, которые вывел интерактор. Однако, интерактор выведет полные входные данные в начале, и после этого вы должны будете вывести ответ. Поэтому вы должны решать задачу так, как если бы вы решали обычную, не интерактивную задачу, потому что у вас не будет никакого процесса взаимодействия. Единственная вещь, про которую вы не должны забыть — это сбросить буфер выходного потока после вывода ответа. Иначе ваше решение может получить вердикт «Решение «зависло»». Обратитесь к <a href="https://codeforces.com/blog/entry/45307">руководству по интерактивным задачам</a> для более детальной информации про сброс буфера выходного потока.</span></p><p>В первой строке находится два целых числа $$$m$$$ и $$$k$$$ ($$$5 \leq m \leq 1000$$$, $$$7 \leq k \leq 1000$$$) — количество человек и количество запомненных моментов.</p><p>Следующие $$$k$$$ строк содержат запомненные координаты. $$$i$$$-я из этих строк содержит $$$m$$$ целых чисел от $$$1$$$ до $$$10^6$$$ (включительно), обозначающих координаты, которые запомнила Cirno в момент времени $$$i-1$$$.</p><p>Гарантируется, что входные данные валидные (то есть только одно целое число было изменено на другое в соответствии с условием задачи). Также гарантируется, что $$$1 \le v_i \le 1000$$$ для всех $$$1 \leq i \leq m$$$.</p><p><span class="tex-font-style-bf">Формат теста для взлома</span>:</p><p>В первой строке должно находиться два целых числа $$$m$$$ и $$$k$$$ ($$$5 \leq m \leq 1000$$$, $$$7 \leq k \leq 1000$$$) — количество человек и количество запомненных моментов.</p><p>Во второй строке должно находиться $$$m$$$ целых чисел $$$x_0, x_1, \dots,x_{m - 1}$$$ ($$$1 \le x_i \le 10^6$$$), где $$$x_i$$$ это изначальная координата $$$i$$$-о человека.</p><p>В третьей строке должно находиться $$$m$$$ целых чисел $$$v_0, v_1, \dots,v_{m - 1}$$$ ($$$1 \le v_i \le 1000$$$), где $$$v_i$$$ это скорость $$$i$$$-о человека. Должно быть выполнено, что $$$x_i + (k-1) v_i \leq 10^6$$$ для всех $$$0 \leq i &lt; m$$$.</p><p>Каждая из следующих $$$k$$$ строк должна содержать $$$m$$$ целых чисел. $$$i$$$-я строка должна содержать $$$m$$$ различных целых чисел $$$p_0, p_1, \ldots, p_{m-1}$$$ ($$$0 \leq p_j &lt; m$$$). Их значение: $$$j$$$-е целое число во входных данных в момент времени $$$i$$$ это координата человека $$$p_{j}$$$.</p><p>В последней строке должно находиться три целых числа $$$y$$$, $$$i$$$, $$$c$$$. Cirno поменяла координату $$$i$$$-о человека в момент времени $$$y$$$ на $$$c$$$ ($$$1 \leq y \leq k-2$$$, $$$0 \leq i \leq m - 1$$$, $$$1 \leq c \leq 10^6$$$, $$$c \neq x_i + y \cdot v_i$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственную строку с двумя целыми числами $$$y$$$, $$$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 6 9 9 6 9 10 7 10 8 10 11 11 11 10 8 12 12 12 12 9 14 13 12 10 13 11 14 16 14 14 12 15 18 15 15 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 13 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте изначальные координаты людей это $$$9$$$, $$$6$$$, $$$6$$$, $$$9$$$, $$$9$$$ и их скорости это $$$1$$$, $$$2$$$, $$$1$$$, $$$1$$$, $$$1$$$. Поэтому несложно заметить, что в момент времени $$$4$$$ одна координата была изменена c $$$13$$$ на $$$12$$$.</p><p>Это первый тест, записанный в формате для взломов:</p><pre class="verbatim"><br/>5 7<br/>9 6 6 9 9<br/>1 2 1 1 1<br/>2 3 4 1 0<br/>0 2 3 1 4<br/>4 3 0 1 2<br/>1 3 4 0 2<br/>1 4 0 2 3<br/>2 4 1 3 0<br/>2 4 1 3 0<br/>4 0 12<br/></pre></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b4c998bac08c85200774beb72680dc1f"/> <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="3fe66514c760cbfa0a037863c569968d78f9afa9"/> <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='b4c998bac08c85200774beb72680dc1f'>&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%2F1545%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='b4c998bac08c85200774beb72680dc1f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1545">Codeforces Round 732 (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='b4c998bac08c85200774beb72680dc1f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1545/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='b4c998bac08c85200774beb72680dc1f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1042720"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b4c998bac08c85200774beb72680dc1f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1042720"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92482" title="Codeforces Round #732" target="_blank">Codeforces Round #732 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13990" resourceName="Codeforces Round #732" resourceManual="true" src="//codeforces.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/92739" title="Codeforces Round #732 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13996" resourceName="Codeforces Round #732 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/1545">Задачи</a></li> <li><a href="/contest/1545/submit">Отослать</a></li> <li><a href="/contest/1545/my">Мои посылки</a></li> <li><a href="/contest/1545/status">Статус</a></li> <li><a href="/contest/1545/hacks">Взломы</a></li> <li><a href="/contest/1545/room/1">Комната</a></li> <li><a href="/contest/1545/standings">Положение</a></li> <li><a href="/contest/1545/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9f643dd837b52850c10ce5ebec44a7308d356986"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. AquaMoon и неправильная координата</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Cirno дала AquaMoon задачу. Есть $$$m$$$ человек, пронумерованных целыми числами от $$$0$$$ до $$$m - 1$$$. Они стоят на координатной прямой в точках с положительными целочисленными координатами. Они смотрят в направлении увеличения координат.</p><p>В этот момент все начинают бежать с фиксированной скоростью в направлении увеличения координат. Изначальная координата $$$i$$$-о человека на прямой это $$$x_i$$$, а скорость $$$i$$$-о человека это $$$v_i$$$. Поэтому координата $$$i$$$-о человека в момент времени $$$t$$$ будет $$$x_i + t \cdot v_i$$$.</p><p>Cirno запомнила координаты всех $$$m$$$ человек в $$$k$$$ последовательных целочисленных моментах времени от $$$0$$$ до $$$k - 1$$$. В каждый момент координаты всех $$$m$$$ человек были запомнены в <span class="tex-font-style-bf">произвольном порядке</span>.</p><p>Чтобы сделать задачу более веселой, Cirno изменила одну из координат в момент времени $$$y$$$ ($$$0 &lt; y &lt; k-1$$$) на <span class="tex-font-style-bf">другое</span> целое число.</p><p>AquaMoon хочет найти момент времени $$$y$$$ и изначальную координату $$$p$$$ перед изменением. К сожалению, она совсем не программист. Поэтому она не смогла решить эту задачу. Можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p><span class="tex-font-style-bf">Эта задача сделана как интерактивная. Это означает, что ваше решение будет считывать входные данные, которые вывел интерактор. Однако, интерактор выведет полные входные данные в начале, и после этого вы должны будете вывести ответ. Поэтому вы должны решать задачу так, как если бы вы решали обычную, не интерактивную задачу, потому что у вас не будет никакого процесса взаимодействия. Единственная вещь, про которую вы не должны забыть — это сбросить буфер выходного потока после вывода ответа. Иначе ваше решение может получить вердикт «Решение «зависло»». Обратитесь к <a href="https://codeforces.com/blog/entry/45307">руководству по интерактивным задачам</a> для более детальной информации про сброс буфера выходного потока.</span></p><p>В первой строке находится два целых числа $$$m$$$ и $$$k$$$ ($$$5 \leq m \leq 1000$$$, $$$7 \leq k \leq 1000$$$) — количество человек и количество запомненных моментов.</p><p>Следующие $$$k$$$ строк содержат запомненные координаты. $$$i$$$-я из этих строк содержит $$$m$$$ целых чисел от $$$1$$$ до $$$10^6$$$ (включительно), обозначающих координаты, которые запомнила Cirno в момент времени $$$i-1$$$.</p><p>Гарантируется, что входные данные валидные (то есть только одно целое число было изменено на другое в соответствии с условием задачи). Также гарантируется, что $$$1 \le v_i \le 1000$$$ для всех $$$1 \leq i \leq m$$$.</p><p><span class="tex-font-style-bf">Формат теста для взлома</span>:</p><p>В первой строке должно находиться два целых числа $$$m$$$ и $$$k$$$ ($$$5 \leq m \leq 1000$$$, $$$7 \leq k \leq 1000$$$) — количество человек и количество запомненных моментов.</p><p>Во второй строке должно находиться $$$m$$$ целых чисел $$$x_0, x_1, \dots,x_{m - 1}$$$ ($$$1 \le x_i \le 10^6$$$), где $$$x_i$$$ это изначальная координата $$$i$$$-о человека.</p><p>В третьей строке должно находиться $$$m$$$ целых чисел $$$v_0, v_1, \dots,v_{m - 1}$$$ ($$$1 \le v_i \le 1000$$$), где $$$v_i$$$ это скорость $$$i$$$-о человека. Должно быть выполнено, что $$$x_i + (k-1) v_i \leq 10^6$$$ для всех $$$0 \leq i &lt; m$$$.</p><p>Каждая из следующих $$$k$$$ строк должна содержать $$$m$$$ целых чисел. $$$i$$$-я строка должна содержать $$$m$$$ различных целых чисел $$$p_0, p_1, \ldots, p_{m-1}$$$ ($$$0 \leq p_j &lt; m$$$). Их значение: $$$j$$$-е целое число во входных данных в момент времени $$$i$$$ это координата человека $$$p_{j}$$$.</p><p>В последней строке должно находиться три целых числа $$$y$$$, $$$i$$$, $$$c$$$. Cirno поменяла координату $$$i$$$-о человека в момент времени $$$y$$$ на $$$c$$$ ($$$1 \leq y \leq k-2$$$, $$$0 \leq i \leq m - 1$$$, $$$1 \leq c \leq 10^6$$$, $$$c \neq x_i + y \cdot v_i$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственную строку с двумя целыми числами $$$y$$$, $$$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 6 9 9 6 9 10 7 10 8 10 11 11 11 10 8 12 12 12 12 9 14 13 12 10 13 11 14 16 14 14 12 15 18 15 15 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 13 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте изначальные координаты людей это $$$9$$$, $$$6$$$, $$$6$$$, $$$9$$$, $$$9$$$ и их скорости это $$$1$$$, $$$2$$$, $$$1$$$, $$$1$$$, $$$1$$$. Поэтому несложно заметить, что в момент времени $$$4$$$ одна координата была изменена c $$$13$$$ на $$$12$$$.</p><p>Это первый тест, записанный в формате для взломов:</p><pre class="verbatim"><br />5 7<br />9 6 6 9 9<br />1 2 1 1 1<br />2 3 4 1 0<br />0 2 3 1 4<br />4 3 0 1 2<br />1 3 4 0 2<br />1 4 0 2 3<br />2 4 1 3 0<br />2 4 1 3 0<br />4 0 12<br /></pre></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c7e9fa1f0022',t:'MTY5NjY2NzQxNC4xNTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*3000"]
1545E1
1545
E1
ru
E1. AquaMoon и остановка времени (простая версия)
<div class="problem-statement"><div class="header"><div class="title">E1. AquaMoon и остановка времени (простая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Обратите внимание, что различия между простой и сложной версиями заключаются в ограничении на $$$n$$$ и в ограничении по времени. Вы можете делать взломы только если обе версии задачи решены.</span></p><p>AquaMoon узнала, что призраки собираются нападать на туристов на пешеходной улице. К сожалению, в этот раз призракам удается скрываться за невидимым барьером, поэтому она не может уничтожить их. Все что она может сделать это спасти от призраков любого человека оказавшегося на улице.</p><p>Пешеходная улица может быть представлена как координатная прямая. Есть один человек, который передвигается по ней. В момент времени $$$0$$$ он находится в координате $$$x$$$, двигаясь со скоростью $$$1$$$ координата в секунду. В частности, в момент времени $$$i$$$ человек будет в координате $$$x+i$$$.</p><p>Призраки собираются совершить $$$n$$$ нападений на улицу. $$$i$$$-е нападение будет длиться с момента времени $$$tl_i-1+10^{-18}$$$ до момента времени $$$tr_i+1-10^{-18}$$$ (не включительно) и будет убивать людей с координатами от $$$l_i-1+10^{-18}$$$ до $$$r_i+1-10^{-18}$$$ (не включительно). Формально это означает, что человек, чья координата находится в интервале $$$(l_i-1+10^{-18},r_i+1-10^{-18})$$$ в любой из моментов времени из интервала $$$(tl_i-1+10^{-18},tr_i+1-10^{-18})$$$ умрет.</p><p>Чтобы спасти человека на улице, AquaMoon может остановить время в любой момент времени $$$t$$$ и затем переместить человека из его текущей координаты $$$x$$$ в любую координату $$$y$$$ ($$$t$$$, $$$x$$$ и $$$y$$$ не обязательно целые числа). Это перемещение будет стоить для AquaMoon $$$|x-y|$$$ энергии. Перемещение является непрерывным, поэтому если существует координата под нападением между координатами $$$x$$$ и $$$y$$$ в момент времени $$$t$$$, человек <span class="tex-font-style-bf">также умрет</span>.</p><p>AquaMoon хочет узнать какое минимальное количество энергии она должна потратить, чтобы спасти человека на улице от всех $$$n$$$ нападений. Она не очень хороша в программировании. Как ее друг, можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$n$$$ ($$$1\le n\le 2000$$$) — количество нападений.</p><p>В следующей строке находится единственное целое число $$$x$$$ ($$$1\le x\le 10^6$$$) — изначальная координата человека.</p><p>В следующих $$$n$$$ строках содержится по четыре целых числа $$$tl_i$$$, $$$tr_i$$$, $$$l_i$$$, $$$r_i$$$ ($$$1\le tl_i\le tr_i\le 10^6$$$, $$$1\le l_i\le r_i\le 10^6$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число — минимальное количество энергии, которое AquaMoon должна потратить, округленное до ближайшего целого числа (если есть два ближайших целых числа вы должны округлить ответ до наибольшего из них).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 1 2 1 2 2 3 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 1 4 1 2 1 4 4 15 6 7 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8</pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 5 1 1 4 10 1 4 1 2 3 13 1 10 7 19 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 14</pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 5 78 96 76 91 6 16 18 37 53 63 40 56 83 88 21 38 72 75 17 24 63 63 53 60 34 46 60 60 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 20</pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="8f4da5e2099a7b4449f57645f0e05339"/> <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="3fe66514c760cbfa0a037863c569968d78f9afa9"/> <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='8f4da5e2099a7b4449f57645f0e05339'>&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%2F1545%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='8f4da5e2099a7b4449f57645f0e05339'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1545">Codeforces Round 732 (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='8f4da5e2099a7b4449f57645f0e05339'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1545/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *3500 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8f4da5e2099a7b4449f57645f0e05339'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1042721"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8f4da5e2099a7b4449f57645f0e05339'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1042721"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92482" title="Codeforces Round #732" target="_blank">Codeforces Round #732 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13990" resourceName="Codeforces Round #732" resourceManual="true" src="//codeforces.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/92739" title="Codeforces Round #732 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13996" resourceName="Codeforces Round #732 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/1545">Задачи</a></li> <li><a href="/contest/1545/submit">Отослать</a></li> <li><a href="/contest/1545/my">Мои посылки</a></li> <li><a href="/contest/1545/status">Статус</a></li> <li><a href="/contest/1545/hacks">Взломы</a></li> <li><a href="/contest/1545/room/1">Комната</a></li> <li><a href="/contest/1545/standings">Положение</a></li> <li><a href="/contest/1545/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_7961e174592f3edb811a4fc08110de7e905ef29e"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. AquaMoon и остановка времени (простая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Обратите внимание, что различия между простой и сложной версиями заключаются в ограничении на $$$n$$$ и в ограничении по времени. Вы можете делать взломы только если обе версии задачи решены.</span></p><p>AquaMoon узнала, что призраки собираются нападать на туристов на пешеходной улице. К сожалению, в этот раз призракам удается скрываться за невидимым барьером, поэтому она не может уничтожить их. Все что она может сделать это спасти от призраков любого человека оказавшегося на улице.</p><p>Пешеходная улица может быть представлена как координатная прямая. Есть один человек, который передвигается по ней. В момент времени $$$0$$$ он находится в координате $$$x$$$, двигаясь со скоростью $$$1$$$ координата в секунду. В частности, в момент времени $$$i$$$ человек будет в координате $$$x+i$$$.</p><p>Призраки собираются совершить $$$n$$$ нападений на улицу. $$$i$$$-е нападение будет длиться с момента времени $$$tl_i-1+10^{-18}$$$ до момента времени $$$tr_i+1-10^{-18}$$$ (не включительно) и будет убивать людей с координатами от $$$l_i-1+10^{-18}$$$ до $$$r_i+1-10^{-18}$$$ (не включительно). Формально это означает, что человек, чья координата находится в интервале $$$(l_i-1+10^{-18},r_i+1-10^{-18})$$$ в любой из моментов времени из интервала $$$(tl_i-1+10^{-18},tr_i+1-10^{-18})$$$ умрет.</p><p>Чтобы спасти человека на улице, AquaMoon может остановить время в любой момент времени $$$t$$$ и затем переместить человека из его текущей координаты $$$x$$$ в любую координату $$$y$$$ ($$$t$$$, $$$x$$$ и $$$y$$$ не обязательно целые числа). Это перемещение будет стоить для AquaMoon $$$|x-y|$$$ энергии. Перемещение является непрерывным, поэтому если существует координата под нападением между координатами $$$x$$$ и $$$y$$$ в момент времени $$$t$$$, человек <span class="tex-font-style-bf">также умрет</span>.</p><p>AquaMoon хочет узнать какое минимальное количество энергии она должна потратить, чтобы спасти человека на улице от всех $$$n$$$ нападений. Она не очень хороша в программировании. Как ее друг, можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$n$$$ ($$$1\le n\le 2000$$$) — количество нападений.</p><p>В следующей строке находится единственное целое число $$$x$$$ ($$$1\le x\le 10^6$$$) — изначальная координата человека.</p><p>В следующих $$$n$$$ строках содержится по четыре целых числа $$$tl_i$$$, $$$tr_i$$$, $$$l_i$$$, $$$r_i$$$ ($$$1\le tl_i\le tr_i\le 10^6$$$, $$$1\le l_i\le r_i\le 10^6$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число — минимальное количество энергии, которое AquaMoon должна потратить, округленное до ближайшего целого числа (если есть два ближайших целых числа вы должны округлить ответ до наибольшего из них).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 1 2 1 2 2 3 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 1 4 1 2 1 4 4 15 6 7 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8</pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 5 1 1 4 10 1 4 1 2 3 13 1 10 7 19 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 14</pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 5 78 96 76 91 6 16 18 37 53 63 40 56 83 88 21 38 72 75 17 24 63 63 53 60 34 46 60 60 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 20</pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E1]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c7f24e6d9d75',t:'MTY5NjY2NzQxNS41MTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3500"]
1545E2
1545
E2
ru
E2. AquaMoon и остановка времени (сложная версия)
<div class="problem-statement"><div class="header"><div class="title">E2. AquaMoon и остановка времени (сложная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>7 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Обратите внимание, что различия между простой и сложной версиями заключаются в ограничении на $$$n$$$ и в ограничении по времени. Вы можете делать взломы только если обе версии задачи решены.</span></p><p>AquaMoon узнала, что призраки собираются нападать на туристов на пешеходной улице. К сожалению, в этот раз призракам удается скрываться за невидимым барьером, поэтому она не может уничтожить их. Все что она может сделать это спасти от призраков любого человека оказавшегося на улице.</p><p>Пешеходная улица может быть представлена как координатная прямая. Есть один человек, который передвигается по ней. В момент времени $$$0$$$ он находится в координате $$$x$$$, двигаясь со скоростью $$$1$$$ координата в секунду. В частности, в момент времени $$$i$$$ человек будет в координате $$$x+i$$$.</p><p>Призраки собираются совершить $$$n$$$ нападений на улицу. $$$i$$$-е нападение будет длиться с момента времени $$$tl_i-1+10^{-18}$$$ до момента времени $$$tr_i+1-10^{-18}$$$ (не включительно) и будет убивать людей с координатами от $$$l_i-1+10^{-18}$$$ до $$$r_i+1-10^{-18}$$$ (не включительно). Формально это означает, что человек, чья координата находится в интервале $$$(l_i-1+10^{-18},r_i+1-10^{-18})$$$ в любой из моментов времени из интервала $$$(tl_i-1+10^{-18},tr_i+1-10^{-18})$$$ умрет.</p><p>Чтобы спасти человека на улице, AquaMoon может остановить время в любой момент времени $$$t$$$ и затем переместить человека из его текущей координаты $$$x$$$ в любую координату $$$y$$$ ($$$t$$$, $$$x$$$ и $$$y$$$ не обязательно целые числа). Это перемещение будет стоить для AquaMoon $$$|x-y|$$$ энергии. Перемещение является непрерывным, поэтому если существует координата под нападением между координатами $$$x$$$ и $$$y$$$ в момент времени $$$t$$$, человек <span class="tex-font-style-bf">также умрет</span>.</p><p>AquaMoon хочет узнать какое минимальное количество энергии она должна потратить, чтобы спасти человека на улице от всех $$$n$$$ нападений. Она не очень хороша в программировании. Как ее друг, можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$n$$$ ($$$1\le n\le 2 \cdot 10^5$$$) — количество нападений.</p><p>В следующей строке находится единственное целое число $$$x$$$ ($$$1\le x\le 10^6$$$) — изначальная координата человека.</p><p>В следующих $$$n$$$ строках содержится по четыре целых числа $$$tl_i$$$, $$$tr_i$$$, $$$l_i$$$, $$$r_i$$$ ($$$1\le tl_i\le tr_i\le 10^6$$$, $$$1\le l_i\le r_i\le 10^6$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число — минимальное количество энергии, которое AquaMoon должна потратить, округленное до ближайшего целого числа (если есть два ближайших целых числа вы должны округлить ответ до наибольшего из них).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 1 2 1 2 2 3 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 1 4 1 2 1 4 4 15 6 7 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8</pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 5 1 1 4 10 1 4 1 2 3 13 1 10 7 19 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 14</pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 5 78 96 76 91 6 16 18 37 53 63 40 56 83 88 21 38 72 75 17 24 63 63 53 60 34 46 60 60 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 20</pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="23a9d920616967215a0377f8b8abd718"/> <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="3fe66514c760cbfa0a037863c569968d78f9afa9"/> <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='23a9d920616967215a0377f8b8abd718'>&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%2F1545%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='23a9d920616967215a0377f8b8abd718'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1545">Codeforces Round 732 (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='23a9d920616967215a0377f8b8abd718'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1545/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *3500 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='23a9d920616967215a0377f8b8abd718'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1042722"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='23a9d920616967215a0377f8b8abd718'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1042722"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92482" title="Codeforces Round #732" target="_blank">Codeforces Round #732 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13990" resourceName="Codeforces Round #732" resourceManual="true" src="//codeforces.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/92739" title="Codeforces Round #732 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13996" resourceName="Codeforces Round #732 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/1545">Задачи</a></li> <li><a href="/contest/1545/submit">Отослать</a></li> <li><a href="/contest/1545/my">Мои посылки</a></li> <li><a href="/contest/1545/status">Статус</a></li> <li><a href="/contest/1545/hacks">Взломы</a></li> <li><a href="/contest/1545/room/1">Комната</a></li> <li><a href="/contest/1545/standings">Положение</a></li> <li><a href="/contest/1545/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d6591cfacc8aca74e2c8faf25ccd2cdcd366d56a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. AquaMoon и остановка времени (сложная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>7 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>1024 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Обратите внимание, что различия между простой и сложной версиями заключаются в ограничении на $$$n$$$ и в ограничении по времени. Вы можете делать взломы только если обе версии задачи решены.</span></p><p>AquaMoon узнала, что призраки собираются нападать на туристов на пешеходной улице. К сожалению, в этот раз призракам удается скрываться за невидимым барьером, поэтому она не может уничтожить их. Все что она может сделать это спасти от призраков любого человека оказавшегося на улице.</p><p>Пешеходная улица может быть представлена как координатная прямая. Есть один человек, который передвигается по ней. В момент времени $$$0$$$ он находится в координате $$$x$$$, двигаясь со скоростью $$$1$$$ координата в секунду. В частности, в момент времени $$$i$$$ человек будет в координате $$$x+i$$$.</p><p>Призраки собираются совершить $$$n$$$ нападений на улицу. $$$i$$$-е нападение будет длиться с момента времени $$$tl_i-1+10^{-18}$$$ до момента времени $$$tr_i+1-10^{-18}$$$ (не включительно) и будет убивать людей с координатами от $$$l_i-1+10^{-18}$$$ до $$$r_i+1-10^{-18}$$$ (не включительно). Формально это означает, что человек, чья координата находится в интервале $$$(l_i-1+10^{-18},r_i+1-10^{-18})$$$ в любой из моментов времени из интервала $$$(tl_i-1+10^{-18},tr_i+1-10^{-18})$$$ умрет.</p><p>Чтобы спасти человека на улице, AquaMoon может остановить время в любой момент времени $$$t$$$ и затем переместить человека из его текущей координаты $$$x$$$ в любую координату $$$y$$$ ($$$t$$$, $$$x$$$ и $$$y$$$ не обязательно целые числа). Это перемещение будет стоить для AquaMoon $$$|x-y|$$$ энергии. Перемещение является непрерывным, поэтому если существует координата под нападением между координатами $$$x$$$ и $$$y$$$ в момент времени $$$t$$$, человек <span class="tex-font-style-bf">также умрет</span>.</p><p>AquaMoon хочет узнать какое минимальное количество энергии она должна потратить, чтобы спасти человека на улице от всех $$$n$$$ нападений. Она не очень хороша в программировании. Как ее друг, можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$n$$$ ($$$1\le n\le 2 \cdot 10^5$$$) — количество нападений.</p><p>В следующей строке находится единственное целое число $$$x$$$ ($$$1\le x\le 10^6$$$) — изначальная координата человека.</p><p>В следующих $$$n$$$ строках содержится по четыре целых числа $$$tl_i$$$, $$$tr_i$$$, $$$l_i$$$, $$$r_i$$$ ($$$1\le tl_i\le tr_i\le 10^6$$$, $$$1\le l_i\le r_i\le 10^6$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число — минимальное количество энергии, которое AquaMoon должна потратить, округленное до ближайшего целого числа (если есть два ближайших целых числа вы должны округлить ответ до наибольшего из них).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 1 1 2 1 2 2 3 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2</pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 1 4 1 2 1 4 4 15 6 7 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8</pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 1 5 1 1 4 10 1 4 1 2 3 13 1 10 7 19 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 14</pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 5 78 96 76 91 6 16 18 37 53 63 40 56 83 88 21 38 72 75 17 24 63 63 53 60 34 46 60 60 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 20</pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E2]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c7faae5d4985',t:'MTY5NjY2NzQxNi44NjUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3500"]
1545F
1545
F
ru
F. AquaMoon и картофель
<div class="problem-statement"><div class="header"><div class="title">F. AquaMoon и картофель</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>7 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У AquaMoon есть три массива $$$a$$$, $$$b$$$, $$$c$$$ длины $$$n$$$, состоящие из целых чисел. Выполнено, что $$$1 \leq a_i, b_i, c_i \leq n$$$ для всех $$$i$$$.</p><p>Чтобы ускорить выращивание картофеля, она организует свою ферму, основываясь на этих трех массивах. Сейчас она хочет выполнить $$$m$$$ операций, чтобы посчитать сколько картофелин она получит. Каждая операция будет иметь один из двух типов:</p><ol> <li> AquaMoon реорганизует ферму и делает $$$k$$$-й элемент массива $$$a$$$ равным $$$x$$$. Другими словами, она выполняет присваивание $$$a_k := x$$$. </li><li> Дано положительное целое число $$$r$$$. AquaMoon получает картофелину за каждую тройку $$$(i,j,k)$$$, такую что $$$1\le i&lt;j&lt;k\le r$$$ и $$$b_{a_i}=a_j=c_{a_k}$$$. Посчитайте количество таких троек. </li></ol><p>Поскольку AquaMoon очень занята поиском библиотеки, помогите ей выполнить все операции.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$, $$$m$$$ ($$$1\le n\le 2\cdot10^5$$$, $$$1\le m\le 5\cdot10^4$$$).</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1, a_2, \dots,a_n$$$ ($$$1\le a_i\le n$$$).</p><p>В третьей строке находится $$$n$$$ целых чисел $$$b_1, b_2, \dots,b_n$$$ ($$$1\le b_i\le n$$$).</p><p>В четвертой строке находится $$$n$$$ целых чисел $$$c_1, c_2, \dots,c_n$$$ ($$$1\le c_i\le n$$$).</p><p>Следующие $$$m$$$ строк описывают операции, $$$i$$$-я строка описывает $$$i$$$-ю операцию в одном из двух форматов:</p><ul> <li> "$$$1\ k\ x$$$" ($$$1\le k,x\le n$$$) для операции первого типа. </li><li> "$$$2\ r$$$" ($$$1\le r\le n$$$) для операции второго типа. </li></ul><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> 5 4 1 2 3 4 5 2 3 4 5 1 5 1 2 3 4 2 5 1 2 3 2 4 2 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 0 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первой операции все подходящие тройки:</p><ul> <li> $$$i=1$$$, $$$j=2$$$, $$$k=3$$$ </li><li> $$$i=2$$$, $$$j=3$$$, $$$k=4$$$ </li><li> $$$i=3$$$, $$$j=4$$$, $$$k=5$$$ </li></ul><p>Не существует подходящих троек для третьей операции.</p><p>Для четвертой операции все подходящие тройки:</p><ul> <li> $$$i=2$$$, $$$j=4$$$, $$$k=5$$$ </li><li> $$$i=3$$$, $$$j=4$$$, $$$k=5$$$ </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="28ab0296a4e7d762b2a63b1790fe0130"/> <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="3fe66514c760cbfa0a037863c569968d78f9afa9"/> <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='28ab0296a4e7d762b2a63b1790fe0130'>&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%2F1545%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='28ab0296a4e7d762b2a63b1790fe0130'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1545">Codeforces Round 732 (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='28ab0296a4e7d762b2a63b1790fe0130'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1545/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='28ab0296a4e7d762b2a63b1790fe0130'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1042723"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='28ab0296a4e7d762b2a63b1790fe0130'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1042723"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92482" title="Codeforces Round #732" target="_blank">Codeforces Round #732 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13990" resourceName="Codeforces Round #732" resourceManual="true" src="//codeforces.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/92739" title="Codeforces Round #732 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13996" resourceName="Codeforces Round #732 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/1545">Задачи</a></li> <li><a href="/contest/1545/submit">Отослать</a></li> <li><a href="/contest/1545/my">Мои посылки</a></li> <li><a href="/contest/1545/status">Статус</a></li> <li><a href="/contest/1545/hacks">Взломы</a></li> <li><a href="/contest/1545/room/1">Комната</a></li> <li><a href="/contest/1545/standings">Положение</a></li> <li><a href="/contest/1545/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_cd0492b9f07d8c620d105a7fc21676d5ff8c11c6"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. AquaMoon и картофель</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>7 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У AquaMoon есть три массива $$$a$$$, $$$b$$$, $$$c$$$ длины $$$n$$$, состоящие из целых чисел. Выполнено, что $$$1 \leq a_i, b_i, c_i \leq n$$$ для всех $$$i$$$.</p><p>Чтобы ускорить выращивание картофеля, она организует свою ферму, основываясь на этих трех массивах. Сейчас она хочет выполнить $$$m$$$ операций, чтобы посчитать сколько картофелин она получит. Каждая операция будет иметь один из двух типов:</p><ol> <li> AquaMoon реорганизует ферму и делает $$$k$$$-й элемент массива $$$a$$$ равным $$$x$$$. Другими словами, она выполняет присваивание $$$a_k := x$$$. </li><li> Дано положительное целое число $$$r$$$. AquaMoon получает картофелину за каждую тройку $$$(i,j,k)$$$, такую что $$$1\le i&lt;j&lt;k\le r$$$ и $$$b_{a_i}=a_j=c_{a_k}$$$. Посчитайте количество таких троек. </li></ol><p>Поскольку AquaMoon очень занята поиском библиотеки, помогите ей выполнить все операции.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$, $$$m$$$ ($$$1\le n\le 2\cdot10^5$$$, $$$1\le m\le 5\cdot10^4$$$).</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1, a_2, \dots,a_n$$$ ($$$1\le a_i\le n$$$).</p><p>В третьей строке находится $$$n$$$ целых чисел $$$b_1, b_2, \dots,b_n$$$ ($$$1\le b_i\le n$$$).</p><p>В четвертой строке находится $$$n$$$ целых чисел $$$c_1, c_2, \dots,c_n$$$ ($$$1\le c_i\le n$$$).</p><p>Следующие $$$m$$$ строк описывают операции, $$$i$$$-я строка описывает $$$i$$$-ю операцию в одном из двух форматов:</p><ul> <li> &quot;$$$1\ k\ x$$$&quot; ($$$1\le k,x\le n$$$) для операции первого типа. </li><li> &quot;$$$2\ r$$$&quot; ($$$1\le r\le n$$$) для операции второго типа. </li></ul><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> 5 4 1 2 3 4 5 2 3 4 5 1 5 1 2 3 4 2 5 1 2 3 2 4 2 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 0 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первой операции все подходящие тройки:</p><ul> <li> $$$i=1$$$, $$$j=2$$$, $$$k=3$$$ </li><li> $$$i=2$$$, $$$j=3$$$, $$$k=4$$$ </li><li> $$$i=3$$$, $$$j=4$$$, $$$k=5$$$ </li></ul><p>Не существует подходящих троек для третьей операции.</p><p>Для четвертой операции все подходящие тройки:</p><ul> <li> $$$i=2$$$, $$$j=4$$$, $$$k=5$$$ </li><li> $$$i=3$$$, $$$j=4$$$, $$$k=5$$$ </li></ul></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c8030fa616e3',t:'MTY5NjY2NzQxOC4yMTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3500"]
1546A
1546
A
ru
A. AquaMoon и два массива
<div class="problem-statement"><div class="header"><div class="title">A. AquaMoon и два массива</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>AquaMoon и Cirno играют в интересную игру с массивами. Cirno приготовил два массива $$$a$$$ и $$$b$$$, оба состоящих из $$$n$$$ неотрицательных целых чисел. AquaMoon может сделать следующую операцию произвольное количество раз (возможно, ноль):</p><ul> <li> Она выбирает два индекса $$$i$$$ и $$$j$$$ ($$$1 \le i, j \le n$$$), затем уменьшает $$$i$$$-й элемент массива $$$a$$$ на $$$1$$$ и увеличивает $$$j$$$-й элемент массива $$$a$$$ на $$$1$$$. В результате значения на $$$i$$$-м и $$$j$$$-м индексах массива $$$a$$$ становятся равными $$$a_i - 1$$$ и $$$a_j + 1$$$, соответственно. Каждый элемент массива $$$a$$$ <span class="tex-font-style-bf">должен оставаться неотрицательным после операции</span>. Если $$$i = j$$$, эта операция никак не поменяет массив $$$a$$$. </li></ul><p>AquaMoon хочет сделать несколько операций, чтобы сделать массивы $$$a$$$ и $$$b$$$ равными. Два массива $$$a$$$ и $$$b$$$ называются равными, если $$$a_i = b_i$$$ для всех $$$1 \leq i \leq n$$$.</p><p>Помогите AquaMoon найти последовательность операций, которая решит ее задачу или установите, что невозможно сделать массивы $$$a$$$ и $$$b$$$ равными.</p><p>Обратите внимание, что <span class="tex-font-style-bf">вы не обязаны минимизировать</span> количество операций.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество наборов входных данных.</p><p>Первая строка описания каждого набора входных данных содержит единственное число $$$n$$$ ($$$1 \leq n \leq 100$$$).</p><p>Во второй строке описания каждого набора входных данных находятся $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$0 \leq a_i \leq 100$$$). <span class="tex-font-style-bf">Сумма всех $$$a_i$$$ не превосходит $$$100$$$.</span></p><p>В третьей строке описания каждого набора входных данных находятся $$$n$$$ целых чисел $$$b_1, b_2, \dots, b_n$$$ ($$$0 \leq b_i \leq 100$$$). <span class="tex-font-style-bf">Сумма всех $$$b_i$$$ не превосходит $$$100$$$.</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">-1</span>» в единственной строке, если невозможно сделать массивы равными после применения некоторой последовательности операций.</p><p>Иначе выведите целое число $$$m$$$ ($$$0 \leq m \leq 100$$$) в первой строке — количество операций. Затем выведите $$$m$$$ строк, в каждой по два целых числа $$$i$$$ и $$$j$$$ — индексы, которые вы выбрали для операции.</p><p>Можно доказать, что если можно сделать два массива равными с помощью некоторой последовательности операций, то существует такая последовательность с $$$m \leq 100$$$.</p><p>Если существует несколько возможных решений, выведите любое.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 4 1 2 3 4 3 1 2 4 2 1 3 2 1 1 0 0 5 4 3 2 1 0 0 1 2 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 2 1 3 1 -1 0 6 1 4 1 4 1 5 1 5 2 5 2 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных мы сделали следующие операции:</p><ul> <li> $$$i = 2$$$, $$$j = 1$$$: $$$[1, 2, 3, 4] \rightarrow [2, 1, 3, 4]$$$; </li><li> $$$i = 3$$$, $$$j = 1$$$: $$$[2, 1, 3, 4] \rightarrow [3, 1, 2, 4]$$$; </li></ul><p>Во втором наборе входных данных невозможно сделать два массива равными.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="d1eaf1ec3c8b2ad8fb440f68d33d8200"/> <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="45cb11cb46147787c541139a8ab89dca9f0eaa38"/> <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='d1eaf1ec3c8b2ad8fb440f68d33d8200'>&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%2F1546%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='d1eaf1ec3c8b2ad8fb440f68d33d8200'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1546">Codeforces Round 732 (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='d1eaf1ec3c8b2ad8fb440f68d33d8200'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1546/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *800 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d1eaf1ec3c8b2ad8fb440f68d33d8200'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1042724"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d1eaf1ec3c8b2ad8fb440f68d33d8200'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1042724"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92482" title="Codeforces Round #732" target="_blank">Codeforces Round #732 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13991" resourceName="Codeforces Round #732" resourceManual="true" src="//codeforces.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/92739" title="Codeforces Round #732 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13997" resourceName="Codeforces Round #732 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/1546">Задачи</a></li> <li><a href="/contest/1546/submit">Отослать</a></li> <li><a href="/contest/1546/my">Мои посылки</a></li> <li><a href="/contest/1546/status">Статус</a></li> <li><a href="/contest/1546/hacks">Взломы</a></li> <li><a href="/contest/1546/room/1">Комната</a></li> <li><a href="/contest/1546/standings">Положение</a></li> <li><a href="/contest/1546/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_93355284c50d2c9cb3ba2b00fcf0cf167c3266d1"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. AquaMoon и два массива</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>AquaMoon и Cirno играют в интересную игру с массивами. Cirno приготовил два массива $$$a$$$ и $$$b$$$, оба состоящих из $$$n$$$ неотрицательных целых чисел. AquaMoon может сделать следующую операцию произвольное количество раз (возможно, ноль):</p><ul> <li> Она выбирает два индекса $$$i$$$ и $$$j$$$ ($$$1 \le i, j \le n$$$), затем уменьшает $$$i$$$-й элемент массива $$$a$$$ на $$$1$$$ и увеличивает $$$j$$$-й элемент массива $$$a$$$ на $$$1$$$. В результате значения на $$$i$$$-м и $$$j$$$-м индексах массива $$$a$$$ становятся равными $$$a_i - 1$$$ и $$$a_j + 1$$$, соответственно. Каждый элемент массива $$$a$$$ <span class="tex-font-style-bf">должен оставаться неотрицательным после операции</span>. Если $$$i = j$$$, эта операция никак не поменяет массив $$$a$$$. </li></ul><p>AquaMoon хочет сделать несколько операций, чтобы сделать массивы $$$a$$$ и $$$b$$$ равными. Два массива $$$a$$$ и $$$b$$$ называются равными, если $$$a_i = b_i$$$ для всех $$$1 \leq i \leq n$$$.</p><p>Помогите AquaMoon найти последовательность операций, которая решит ее задачу или установите, что невозможно сделать массивы $$$a$$$ и $$$b$$$ равными.</p><p>Обратите внимание, что <span class="tex-font-style-bf">вы не обязаны минимизировать</span> количество операций.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество наборов входных данных.</p><p>Первая строка описания каждого набора входных данных содержит единственное число $$$n$$$ ($$$1 \leq n \leq 100$$$).</p><p>Во второй строке описания каждого набора входных данных находятся $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$0 \leq a_i \leq 100$$$). <span class="tex-font-style-bf">Сумма всех $$$a_i$$$ не превосходит $$$100$$$.</span></p><p>В третьей строке описания каждого набора входных данных находятся $$$n$$$ целых чисел $$$b_1, b_2, \dots, b_n$$$ ($$$0 \leq b_i \leq 100$$$). <span class="tex-font-style-bf">Сумма всех $$$b_i$$$ не превосходит $$$100$$$.</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">-1</span>» в единственной строке, если невозможно сделать массивы равными после применения некоторой последовательности операций.</p><p>Иначе выведите целое число $$$m$$$ ($$$0 \leq m \leq 100$$$) в первой строке — количество операций. Затем выведите $$$m$$$ строк, в каждой по два целых числа $$$i$$$ и $$$j$$$ — индексы, которые вы выбрали для операции.</p><p>Можно доказать, что если можно сделать два массива равными с помощью некоторой последовательности операций, то существует такая последовательность с $$$m \leq 100$$$.</p><p>Если существует несколько возможных решений, выведите любое.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 4 1 2 3 4 3 1 2 4 2 1 3 2 1 1 0 0 5 4 3 2 1 0 0 1 2 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 2 1 3 1 -1 0 6 1 4 1 4 1 5 1 5 2 5 2 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных мы сделали следующие операции:</p><ul> <li> $$$i = 2$$$, $$$j = 1$$$: $$$[1, 2, 3, 4] \rightarrow [2, 1, 3, 4]$$$; </li><li> $$$i = 3$$$, $$$j = 1$$$: $$$[2, 1, 3, 4] \rightarrow [3, 1, 2, 4]$$$; </li></ul><p>Во втором наборе входных данных невозможно сделать два массива равными.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c80b6b220c42',t:'MTY5NjY2NzQxOS42MTEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*800"]
1546B
1546
B
ru
B. AquaMoon и украденная строка
<div class="problem-statement"><div class="header"><div class="title">B. AquaMoon и украденная строка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У AquaMoon было $$$n$$$ строк длины $$$m$$$ каждая. $$$n$$$ — <span class="tex-font-style-bf">нечетное</span> число.</p><p>Когда AquaMoon отошла, Cirno попыталась разбить эти $$$n$$$ строк на пары. После того, как она сделала $$$\frac{n-1}{2}$$$ пару, она обнаружила, что осталась ровно одна строка без пары!</p><p>В гневе она перемешала каждую пару строк. Для каждой пары она выбрала некоторые позиции (хотя бы $$$1$$$ и не более, чем $$$m$$$) и обменяла символы в двух строках этой пары на выбранных позициях.</p><p>Например, если $$$m = 6$$$ и две строки «<span class="tex-font-style-tt">abcdef</span>» и «<span class="tex-font-style-tt">xyzklm</span>» в одной паре и Cirno выбрала позиции $$$2$$$, $$$3$$$ и $$$6$$$ она поменяет '<span class="tex-font-style-tt">b</span>' с '<span class="tex-font-style-tt">y</span>', '<span class="tex-font-style-tt">c</span>' с '<span class="tex-font-style-tt">z</span>' и '<span class="tex-font-style-tt">f</span>' с '<span class="tex-font-style-tt">m</span>'. В результате строки станут «<span class="tex-font-style-tt">ayzdem</span>» и «<span class="tex-font-style-tt">xbcklf</span>».</p><p>Затем Cirno украла строку, оставшуюся без пары, и расположила все оставшиеся строки в некотором порядке.</p><p>AquaMoon обнаружила оставшуюся $$$n-1$$$ строку в полном беспорядке. Также, она помнит изначальные $$$n$$$ строк. Она хочет узнать, какую строку украли, но она не очень хороша в программировании. Можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p><span class="tex-font-style-bf">Эта задача сделана как интерактивная. Это означает, что ваше решение будет считывать входные данные, которые вывел интерактор. Однако, интерактор выведет полные входные данные в начале, и после этого вы должны будете вывести ответ. Поэтому вы должны решать задачу так, как если бы вы решали обычную, не интерактивную задачу, потому что у вас не будет никакого процесса взаимодействия. Единственная вещь, про которую вы не должны забыть — это сбросить буфер выходного потока после вывода ответа. Иначе ваше решение может получить вердикт «Решение «зависло»». Обратитесь к <a href="https://codeforces.com/blog/entry/45307">руководству по интерактивным задачам</a> для более детальной информации про сброс буфера выходного потока.</span></p><p>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных содержится два целых числа $$$n$$$, $$$m$$$ ($$$1 \leq n \leq 10^5$$$, $$$1 \leq m \leq 10^5$$$) — количество строк и длина каждой строки, соответственно.</p><p>Следующие $$$n$$$ строк каждая содержат строку длины $$$m$$$, описывающую изначальные $$$n$$$ строк. Все строки состоят из символов латинского алфавита в нижнем регистре.</p><p>Следующая $$$n-1$$$ строка каждая содержит строку длины $$$m$$$, описывающую строки, после того, как Cirno сделала обмены и переставила их.</p><p>Гарантируется, что $$$n$$$ нечетно и что сумма $$$n \cdot m$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p><p><span class="tex-font-style-bf">Формат теста для взлома</span>:</p><p>В первой строке должно находиться единственное целое число $$$t$$$. После этого должно следовать описание $$$t$$$ наборов входных данных в следующем формате:</p><p>В первой строке должно находиться два целых числа $$$n$$$ и $$$m$$$.</p><p>В следующих $$$n$$$ строках должны быть записаны $$$n$$$ строк длины $$$m$$$, описывающих изначальные строки.</p><p>Следующие $$$\frac{n-1}{2}$$$ строк должны описывать пары. Каждая должна содержать в следующем порядке: индекс первой строки $$$i$$$ ($$$1 \leq i \leq n$$$), индекс второй строки $$$j$$$ ($$$1 \leq j \leq n$$$, $$$i \neq j$$$), количество позиций для обмена $$$k$$$ ($$$1 \leq k \leq m$$$) и список из $$$k$$$ позиций, в которых будет сделан обмен ($$$k$$$ различных индексов от $$$1$$$ до $$$m$$$ в любом порядке).</p><p>В последней строке должна находиться перестановка из целых чисел от $$$1$$$ до $$$n$$$, описывающая способ, которым строки будут перемешаны. Строки будут расположены в том порядке, в котором индексы следуют в перестановке, индекс украденной строки при этом будет пропущен.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите украденную строку в единственной строке.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 5 aaaaa bbbbb ccccc aaaaa bbbbb 3 4 aaaa bbbb cccc aabb bbaa 5 6 abcdef uuuuuu kekeke ekekek xyzklm xbcklf eueueu ayzdem ukukuk </pre></div><div class="output"><div class="title">Выходные данные</div><pre> ccccc cccc kekeke </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных в строках «<span class="tex-font-style-tt">aaaaa</span>» и «<span class="tex-font-style-tt">bbbbb</span>» обменяли все позиции и «<span class="tex-font-style-tt">ccccc</span>» является украденной строкой.</p><p>Во втором наборе входных данных в строках «<span class="tex-font-style-tt">aaaa</span>» и «<span class="tex-font-style-tt">bbbb</span>» обменяли первые две позиции и «<span class="tex-font-style-tt">cccc</span>» является украденной строкой.</p><p>Это первый тест, записанный в формате для взломов: </p><pre class="verbatim"><br/>3<br/>3 5<br/>aaaaa<br/>bbbbb<br/>ccccc<br/>1 2 5 1 2 3 4 5<br/>2 1 3<br/>3 4<br/>aaaa<br/>bbbb<br/>cccc<br/>1 2 2 1 2<br/>2 1 3<br/>5 6<br/>abcdef<br/>uuuuuu<br/>kekeke<br/>ekekek<br/>xyzklm<br/>1 5 3 2 3 6<br/>2 4 3 2 4 6<br/>5 4 1 2 3<br/></pre></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="abbce19ab97b13f23716029268c17a97"/> <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="45cb11cb46147787c541139a8ab89dca9f0eaa38"/> <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='abbce19ab97b13f23716029268c17a97'>&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%2F1546%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='abbce19ab97b13f23716029268c17a97'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1546">Codeforces Round 732 (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='abbce19ab97b13f23716029268c17a97'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1546/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='abbce19ab97b13f23716029268c17a97'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1042725"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='abbce19ab97b13f23716029268c17a97'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1042725"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92482" title="Codeforces Round #732" target="_blank">Codeforces Round #732 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13991" resourceName="Codeforces Round #732" resourceManual="true" src="//codeforces.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/92739" title="Codeforces Round #732 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13997" resourceName="Codeforces Round #732 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/1546">Задачи</a></li> <li><a href="/contest/1546/submit">Отослать</a></li> <li><a href="/contest/1546/my">Мои посылки</a></li> <li><a href="/contest/1546/status">Статус</a></li> <li><a href="/contest/1546/hacks">Взломы</a></li> <li><a href="/contest/1546/room/1">Комната</a></li> <li><a href="/contest/1546/standings">Положение</a></li> <li><a href="/contest/1546/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d20d786130cc0106992c54f391a9129944b46f5d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. AquaMoon и украденная строка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У AquaMoon было $$$n$$$ строк длины $$$m$$$ каждая. $$$n$$$ — <span class="tex-font-style-bf">нечетное</span> число.</p><p>Когда AquaMoon отошла, Cirno попыталась разбить эти $$$n$$$ строк на пары. После того, как она сделала $$$\frac{n-1}{2}$$$ пару, она обнаружила, что осталась ровно одна строка без пары!</p><p>В гневе она перемешала каждую пару строк. Для каждой пары она выбрала некоторые позиции (хотя бы $$$1$$$ и не более, чем $$$m$$$) и обменяла символы в двух строках этой пары на выбранных позициях.</p><p>Например, если $$$m = 6$$$ и две строки «<span class="tex-font-style-tt">abcdef</span>» и «<span class="tex-font-style-tt">xyzklm</span>» в одной паре и Cirno выбрала позиции $$$2$$$, $$$3$$$ и $$$6$$$ она поменяет '<span class="tex-font-style-tt">b</span>' с '<span class="tex-font-style-tt">y</span>', '<span class="tex-font-style-tt">c</span>' с '<span class="tex-font-style-tt">z</span>' и '<span class="tex-font-style-tt">f</span>' с '<span class="tex-font-style-tt">m</span>'. В результате строки станут «<span class="tex-font-style-tt">ayzdem</span>» и «<span class="tex-font-style-tt">xbcklf</span>».</p><p>Затем Cirno украла строку, оставшуюся без пары, и расположила все оставшиеся строки в некотором порядке.</p><p>AquaMoon обнаружила оставшуюся $$$n-1$$$ строку в полном беспорядке. Также, она помнит изначальные $$$n$$$ строк. Она хочет узнать, какую строку украли, но она не очень хороша в программировании. Можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p><span class="tex-font-style-bf">Эта задача сделана как интерактивная. Это означает, что ваше решение будет считывать входные данные, которые вывел интерактор. Однако, интерактор выведет полные входные данные в начале, и после этого вы должны будете вывести ответ. Поэтому вы должны решать задачу так, как если бы вы решали обычную, не интерактивную задачу, потому что у вас не будет никакого процесса взаимодействия. Единственная вещь, про которую вы не должны забыть — это сбросить буфер выходного потока после вывода ответа. Иначе ваше решение может получить вердикт «Решение «зависло»». Обратитесь к <a href="https://codeforces.com/blog/entry/45307">руководству по интерактивным задачам</a> для более детальной информации про сброс буфера выходного потока.</span></p><p>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных содержится два целых числа $$$n$$$, $$$m$$$ ($$$1 \leq n \leq 10^5$$$, $$$1 \leq m \leq 10^5$$$) — количество строк и длина каждой строки, соответственно.</p><p>Следующие $$$n$$$ строк каждая содержат строку длины $$$m$$$, описывающую изначальные $$$n$$$ строк. Все строки состоят из символов латинского алфавита в нижнем регистре.</p><p>Следующая $$$n-1$$$ строка каждая содержит строку длины $$$m$$$, описывающую строки, после того, как Cirno сделала обмены и переставила их.</p><p>Гарантируется, что $$$n$$$ нечетно и что сумма $$$n \cdot m$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p><p><span class="tex-font-style-bf">Формат теста для взлома</span>:</p><p>В первой строке должно находиться единственное целое число $$$t$$$. После этого должно следовать описание $$$t$$$ наборов входных данных в следующем формате:</p><p>В первой строке должно находиться два целых числа $$$n$$$ и $$$m$$$.</p><p>В следующих $$$n$$$ строках должны быть записаны $$$n$$$ строк длины $$$m$$$, описывающих изначальные строки.</p><p>Следующие $$$\frac{n-1}{2}$$$ строк должны описывать пары. Каждая должна содержать в следующем порядке: индекс первой строки $$$i$$$ ($$$1 \leq i \leq n$$$), индекс второй строки $$$j$$$ ($$$1 \leq j \leq n$$$, $$$i \neq j$$$), количество позиций для обмена $$$k$$$ ($$$1 \leq k \leq m$$$) и список из $$$k$$$ позиций, в которых будет сделан обмен ($$$k$$$ различных индексов от $$$1$$$ до $$$m$$$ в любом порядке).</p><p>В последней строке должна находиться перестановка из целых чисел от $$$1$$$ до $$$n$$$, описывающая способ, которым строки будут перемешаны. Строки будут расположены в том порядке, в котором индексы следуют в перестановке, индекс украденной строки при этом будет пропущен.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите украденную строку в единственной строке.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 5 aaaaa bbbbb ccccc aaaaa bbbbb 3 4 aaaa bbbb cccc aabb bbaa 5 6 abcdef uuuuuu kekeke ekekek xyzklm xbcklf eueueu ayzdem ukukuk </pre></div><div class="output"><div class="title">Выходные данные</div><pre> ccccc cccc kekeke </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных в строках «<span class="tex-font-style-tt">aaaaa</span>» и «<span class="tex-font-style-tt">bbbbb</span>» обменяли все позиции и «<span class="tex-font-style-tt">ccccc</span>» является украденной строкой.</p><p>Во втором наборе входных данных в строках «<span class="tex-font-style-tt">aaaa</span>» и «<span class="tex-font-style-tt">bbbb</span>» обменяли первые две позиции и «<span class="tex-font-style-tt">cccc</span>» является украденной строкой.</p><p>Это первый тест, записанный в формате для взломов: </p><pre class="verbatim"><br />3<br />3 5<br />aaaaa<br />bbbbb<br />ccccc<br />1 2 5 1 2 3 4 5<br />2 1 3<br />3 4<br />aaaa<br />bbbb<br />cccc<br />1 2 2 1 2<br />2 1 3<br />5 6<br />abcdef<br />uuuuuu<br />kekeke<br />ekekek<br />xyzklm<br />1 5 3 2 3 6<br />2 4 3 2 4 6<br />5 4 1 2 3<br /></pre></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c8143e9916b3',t:'MTY5NjY2NzQyMC45NTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1200"]
1546C
1546
C
ru
C. AquaMoon и странная сортировка
<div class="problem-statement"><div class="header"><div class="title">C. AquaMoon и странная сортировка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У AquaMoon есть $$$n$$$ друзей. Они встали в ряд. $$$i$$$-й слева друг надел футболку с числом $$$a_i$$$, написанным на ней. Каждый друг смотрит в одну из двух сторон налево или направо. В начале все друзья смотрят <span class="tex-font-style-bf">направо</span>.</p><p>AquaMoon может делать операции с друзьями. На каждой операции AquaMoon может выбрать два <span class="tex-font-style-bf">соседних</span> в ряду друга и поменять их местами. После каждой операции оба друга изменяют направление, в котором смотрели, на противоположное: если кто-то смотрел налево, он будет смотреть направо, и наоборот.</p><p>AquaMoon надеется, что после нескольких операций числа, написанные на футболках у $$$n$$$ друзей станут <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>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 50$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — количество друзей Aquamoon.</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^5$$$) — числа, записанные на футболках.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">YES</span>» (без кавычек), если существует возможная последовательность операций; иначе, выведите «<span class="tex-font-style-tt">NO</span>» (без кавычек).</p><p>Вы можете выводить каждую букву в любом регистре (строчную или заглавную).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 4 3 2 5 4 3 3 2 2 5 1 2 3 5 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Возможная последовательность операций для первого набора входных данных:</p><ol> <li> Поменять $$$a_1$$$ и $$$a_2$$$. В результате последовательность чисел $$$3, 4, 2, 5$$$. Друзья смотрят: налево, налево, направо, направо. </li><li> Поменять $$$a_2$$$ и $$$a_3$$$. В результате последовательность чисел $$$3, 2, 4, 5$$$. Друзья смотрят: налево, налево, направо, направо. </li><li> Поменять $$$a_1$$$ и $$$a_2$$$. В результате последовательность чисел $$$2, 3, 4, 5$$$. Друзья смотрят: направо, направо, направо, направо. </li></ol></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="cef73d870854e3b49ad95c13b2f5d881"/> <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="45cb11cb46147787c541139a8ab89dca9f0eaa38"/> <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='cef73d870854e3b49ad95c13b2f5d881'>&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%2F1546%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='cef73d870854e3b49ad95c13b2f5d881'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1546">Codeforces Round 732 (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='cef73d870854e3b49ad95c13b2f5d881'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1546/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='cef73d870854e3b49ad95c13b2f5d881'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1042726"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='cef73d870854e3b49ad95c13b2f5d881'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1042726"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92482" title="Codeforces Round #732" target="_blank">Codeforces Round #732 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13991" resourceName="Codeforces Round #732" resourceManual="true" src="//codeforces.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/92739" title="Codeforces Round #732 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13997" resourceName="Codeforces Round #732 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/1546">Задачи</a></li> <li><a href="/contest/1546/submit">Отослать</a></li> <li><a href="/contest/1546/my">Мои посылки</a></li> <li><a href="/contest/1546/status">Статус</a></li> <li><a href="/contest/1546/hacks">Взломы</a></li> <li><a href="/contest/1546/room/1">Комната</a></li> <li><a href="/contest/1546/standings">Положение</a></li> <li><a href="/contest/1546/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_76efe1acce51e5da4c403163f864297a1dd9eeed"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. AquaMoon и странная сортировка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У AquaMoon есть $$$n$$$ друзей. Они встали в ряд. $$$i$$$-й слева друг надел футболку с числом $$$a_i$$$, написанным на ней. Каждый друг смотрит в одну из двух сторон налево или направо. В начале все друзья смотрят <span class="tex-font-style-bf">направо</span>.</p><p>AquaMoon может делать операции с друзьями. На каждой операции AquaMoon может выбрать два <span class="tex-font-style-bf">соседних</span> в ряду друга и поменять их местами. После каждой операции оба друга изменяют направление, в котором смотрели, на противоположное: если кто-то смотрел налево, он будет смотреть направо, и наоборот.</p><p>AquaMoon надеется, что после нескольких операций числа, написанные на футболках у $$$n$$$ друзей станут <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>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 50$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — количество друзей Aquamoon.</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^5$$$) — числа, записанные на футболках.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">YES</span>» (без кавычек), если существует возможная последовательность операций; иначе, выведите «<span class="tex-font-style-tt">NO</span>» (без кавычек).</p><p>Вы можете выводить каждую букву в любом регистре (строчную или заглавную).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 4 3 2 5 4 3 3 2 2 5 1 2 3 5 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Возможная последовательность операций для первого набора входных данных:</p><ol> <li> Поменять $$$a_1$$$ и $$$a_2$$$. В результате последовательность чисел $$$3, 4, 2, 5$$$. Друзья смотрят: налево, налево, направо, направо. </li><li> Поменять $$$a_2$$$ и $$$a_3$$$. В результате последовательность чисел $$$3, 2, 4, 5$$$. Друзья смотрят: налево, налево, направо, направо. </li><li> Поменять $$$a_1$$$ и $$$a_2$$$. В результате последовательность чисел $$$2, 3, 4, 5$$$. Друзья смотрят: направо, направо, направо, направо. </li></ol></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30:22</span> (j1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;"> <a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/86568/images/ton-100x100.png" alt="TON" title="TON"/></a> <a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/86568/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto"> <div class="datatable" style="background-color: #E1E1E1; padding-bottom: 3px;"> <div class="lt">&nbsp;</div> <div class="rt">&nbsp;</div> <div class="lb">&nbsp;</div> <div class="rb">&nbsp;</div> <div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;"> Списки пользователей <div style="position:absolute;right:0.25em;top:0.35em;"> <span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span> <img class="closed" src="//codeforces.org/s/86568/images/icons/control.png"/> <span class="filter" style="display:none;"> <img class="opened" src="//codeforces.org/s/86568/images/icons/control-270.png"/> <input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/> </span> </div> </div> <div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;"> <div class="ilt">&nbsp;</div> <div class="irt">&nbsp;</div> <table class=""> <thead> <tr> <th>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey")); }); }, "json"); }); }); </script> </div> <script type="application/javascript"> if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) { navigator.serviceWorker.register('/service-worker-86568.js') .then(function (registration) { console.log('Service worker registered: ', registration); }) .catch(function (error) { console.log('Registration failed: ', error); }); } </script> <script>(function(){var js = "window['__CF$cv$params']={r:'8124c81caab39d99',t:'MTY5NjY2NzQyMi4yNzEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\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"]
["\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1500"]
1546D
1546
D
ru
D. AquaMoon и шахматы
<div class="problem-statement"><div class="header"><div class="title">D. AquaMoon и шахматы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Cirno дала AquaMoon шахматную доску размера $$$1 \times n$$$. Ее клетки пронумерованы целыми числами от $$$1$$$ до $$$n$$$ слева направо. Изначально в некоторых клетках находится одна пешка, а остальные клетки свободны.</p><p>На каждой операции AquaMoon может выбрать клетку $$$i$$$ с пешкой и сделать <span class="tex-font-style-bf">любую</span> из следующих операций (если возможно): </p><ul> <li> Переместить пешку из нее в клетку $$$(i+2)$$$, если $$$i+2 \leq n$$$, $$$(i+1)$$$-я клетка занята пешкой, а $$$(i+2)$$$-я клетка свободна. </li><li> Переместить пешку из нее в клетку $$$(i-2)$$$, если $$$i-2 \geq 1$$$, $$$(i-1)$$$-я клетка занята пешкой, а $$$(i-2)$$$-я клетка свободна. </li></ul><p>Дано изначальное состояние шахматной доски. AquaMoon хочет посчитать количество состояний, которые достижимы из начального состояния с помощью некоторой последовательности операций. Но она не очень хороша в программировании. Можете ли вы помочь ей? Поскольку ответ может быть большим, найдите его по модулю $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — размер шахматной доски.</p><p>Во второй строке находится строка, состоящая из $$$n$$$ символов «<span class="tex-font-style-tt">0</span>» или «<span class="tex-font-style-tt">1</span>». Если $$$i$$$-й символ это «<span class="tex-font-style-tt">1</span>», $$$i$$$-я клетка изначальна занята пешкой, иначе $$$i$$$-я клетка изначально свободна.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите количество состояний, которое может быть получено из начального с помощью некоторой последовательности операций по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 6 1 1287 1287 715 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных строки «<span class="tex-font-style-tt">1100</span>», «<span class="tex-font-style-tt">0110</span>» и «<span class="tex-font-style-tt">0011</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="7154fd4855c239614f5a7f50f46f2ab0"/> <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="45cb11cb46147787c541139a8ab89dca9f0eaa38"/> <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='7154fd4855c239614f5a7f50f46f2ab0'>&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%2F1546%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='7154fd4855c239614f5a7f50f46f2ab0'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1546">Codeforces Round 732 (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='7154fd4855c239614f5a7f50f46f2ab0'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1546/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='7154fd4855c239614f5a7f50f46f2ab0'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1042727"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7154fd4855c239614f5a7f50f46f2ab0'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1042727"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92482" title="Codeforces Round #732" target="_blank">Codeforces Round #732 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13991" resourceName="Codeforces Round #732" resourceManual="true" src="//codeforces.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/92739" title="Codeforces Round #732 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13997" resourceName="Codeforces Round #732 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/1546">Задачи</a></li> <li><a href="/contest/1546/submit">Отослать</a></li> <li><a href="/contest/1546/my">Мои посылки</a></li> <li><a href="/contest/1546/status">Статус</a></li> <li><a href="/contest/1546/hacks">Взломы</a></li> <li><a href="/contest/1546/room/1">Комната</a></li> <li><a href="/contest/1546/standings">Положение</a></li> <li><a href="/contest/1546/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_23f6378335183fc6ece0047d1ca73afb123b0b3f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. AquaMoon и шахматы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Cirno дала AquaMoon шахматную доску размера $$$1 \times n$$$. Ее клетки пронумерованы целыми числами от $$$1$$$ до $$$n$$$ слева направо. Изначально в некоторых клетках находится одна пешка, а остальные клетки свободны.</p><p>На каждой операции AquaMoon может выбрать клетку $$$i$$$ с пешкой и сделать <span class="tex-font-style-bf">любую</span> из следующих операций (если возможно): </p><ul> <li> Переместить пешку из нее в клетку $$$(i+2)$$$, если $$$i+2 \leq n$$$, $$$(i+1)$$$-я клетка занята пешкой, а $$$(i+2)$$$-я клетка свободна. </li><li> Переместить пешку из нее в клетку $$$(i-2)$$$, если $$$i-2 \geq 1$$$, $$$(i-1)$$$-я клетка занята пешкой, а $$$(i-2)$$$-я клетка свободна. </li></ul><p>Дано изначальное состояние шахматной доски. AquaMoon хочет посчитать количество состояний, которые достижимы из начального состояния с помощью некоторой последовательности операций. Но она не очень хороша в программировании. Можете ли вы помочь ей? Поскольку ответ может быть большим, найдите его по модулю $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — размер шахматной доски.</p><p>Во второй строке находится строка, состоящая из $$$n$$$ символов «<span class="tex-font-style-tt">0</span>» или «<span class="tex-font-style-tt">1</span>». Если $$$i$$$-й символ это «<span class="tex-font-style-tt">1</span>», $$$i$$$-я клетка изначальна занята пешкой, иначе $$$i$$$-я клетка изначально свободна.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите количество состояний, которое может быть получено из начального с помощью некоторой последовательности операций по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 4 0110 6 011011 5 01010 20 10001111110110111000 20 00110110100110111101 20 11101111011000100010 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 6 1 1287 1287 715 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных строки «<span class="tex-font-style-tt">1100</span>», «<span class="tex-font-style-tt">0110</span>» и «<span class="tex-font-style-tt">0011</span>» могут быть получены из изначального состояния с помощью некоторой последовательности операций.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c824ee22759f',t:'MTY5NjY2NzQyMy41NTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1900"]
1546E
1546
E
ru
E. AquaMoon и перестановки
<div class="problem-statement"><div class="header"><div class="title">E. AquaMoon и перестановки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Cirno подготовила $$$n$$$ массивов длины $$$n$$$ каждый. Каждый массив — это перестановка из $$$n$$$ целых чисел от $$$1$$$ до $$$n$$$. Эти массивы специальные: для всех $$$1 \leq i \leq n$$$, если мы возьмем $$$i$$$-й элемент каждого массива и построим другой массив длины $$$n$$$, состоящий из этих элементов, получившийся массив также будет перестановкой $$$n$$$ чисел от $$$1$$$ до $$$n$$$. Другими словами, если эти $$$n$$$ массивов расположить друг под другом, образовав матрицу с $$$n$$$ строками и $$$n$$$ столбцами, эта матрица будет <a href="https://ru.wikipedia.org/wiki/Латинский_квадрат">латинским квадратом</a>.</p><p>После этого Cirno добавила дополнительные $$$n$$$ массивов, каждый массив также является перестановкой из $$$n$$$ целых чисел от $$$1$$$ до $$$n$$$. Для всех $$$1 \leq i \leq n$$$ существует <span class="tex-font-style-bf">хотя бы одна</span> позиция $$$1 \leq k \leq n$$$, такая что для $$$i$$$-го и $$$(n + i)$$$-го массивов $$$k$$$-е элементы совпадают. Обратите внимание, что массивы с индексами от $$$n + 1$$$ до $$$2n$$$ <span class="tex-font-style-bf">не обязаны</span> образовывать латинский квадрат.</p><p>Также Cirno убедилась, что среди $$$2n$$$ массивов никакие два не равны, то есть для всех пар индексов $$$1 \leq i &lt; j \leq 2n$$$ существует <span class="tex-font-style-bf">хотя бы одна</span> позиция $$$1 \leq k \leq n$$$, такая что в $$$i$$$-м и $$$j$$$-м массивах $$$k$$$-е элементы <span class="tex-font-style-bf">различны</span>.</p><p>В конце Cirno произвольно поменяла порядок, в котором расположены подготовленные $$$2n$$$ массивов.</p><p>AquaMoon называет подмножество всех $$$2n$$$ массивов размера $$$n$$$ <span class="tex-font-style-bf">хорошим</span>, если эти массивы образуют латинский квадрат.</p><p>AquaMoon хочет узнать, сколько хороших подмножеств существует. Поскольку это количество может быть очень большим, найдите его по модулю $$$998\,244\,353$$$. Также она хочет найти любое хорошее подмножество. Можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$5 \leq n \leq 500$$$).</p><p>Затем $$$2n$$$ строк следует. $$$i$$$-я из этих строк содержит $$$n$$$ целых чисел, составляющих $$$i$$$-й массив.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$500$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите две строки.</p><p>В первой строке выведите количество хороших подмножеств по модулю $$$998\,244\,353$$$.</p><p>Во второй строке выведите $$$n$$$ индексов от $$$1$$$ до $$$2n$$$ — индексы $$$n$$$ массивов, которые образуют хорошее подмножество (вы можете вывести их в любом порядке). Если существует несколько возможных ответов — выведите любой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 7 1 2 3 4 5 6 7 2 3 4 5 6 7 1 3 4 5 6 7 1 2 4 5 6 7 1 2 3 5 6 7 1 2 3 4 6 7 1 2 3 4 5 7 1 2 3 4 5 6 1 2 3 4 5 7 6 1 3 4 5 6 7 2 1 4 5 6 7 3 2 1 5 6 7 4 2 3 1 6 7 5 2 3 4 1 7 6 2 3 4 5 1 7 2 3 4 5 6 5 4 5 1 2 3 3 5 2 4 1 1 2 3 4 5 5 2 4 1 3 3 4 5 1 2 2 3 4 5 1 1 3 5 2 4 4 1 3 5 2 2 4 1 3 5 5 1 2 3 4 6 2 3 4 5 6 1 3 1 2 6 4 5 6 1 2 3 4 5 5 6 1 3 2 4 4 3 6 5 2 1 5 6 1 2 3 4 4 5 6 1 2 3 3 4 5 6 1 2 1 2 3 4 5 6 2 5 4 1 6 3 3 2 5 4 1 6 1 4 3 6 5 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 2 3 4 5 6 7 2 1 3 5 6 10 4 1 3 6 7 8 9 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных количество хороших подмножеств равно $$$1$$$. Единственное такое подмножество это подмножество массивов с индексами $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, $$$6$$$, $$$7$$$.</p><p>Во втором наборе входных данных количество хороших подмножеств равно $$$2$$$. Эти подмножества это $$$1$$$, $$$3$$$, $$$5$$$, $$$6$$$, $$$10$$$, а также $$$2$$$, $$$4$$$, $$$7$$$, $$$8$$$, $$$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="b7906a166bad96d0819fd0b9bca2df06"/> <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="45cb11cb46147787c541139a8ab89dca9f0eaa38"/> <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='b7906a166bad96d0819fd0b9bca2df06'>&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%2F1546%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='b7906a166bad96d0819fd0b9bca2df06'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1546">Codeforces Round 732 (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='b7906a166bad96d0819fd0b9bca2df06'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1546/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='b7906a166bad96d0819fd0b9bca2df06'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1042728"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b7906a166bad96d0819fd0b9bca2df06'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1042728"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92482" title="Codeforces Round #732" target="_blank">Codeforces Round #732 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13991" resourceName="Codeforces Round #732" resourceManual="true" src="//codeforces.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/92739" title="Codeforces Round #732 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13997" resourceName="Codeforces Round #732 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/1546">Задачи</a></li> <li><a href="/contest/1546/submit">Отослать</a></li> <li><a href="/contest/1546/my">Мои посылки</a></li> <li><a href="/contest/1546/status">Статус</a></li> <li><a href="/contest/1546/hacks">Взломы</a></li> <li><a href="/contest/1546/room/1">Комната</a></li> <li><a href="/contest/1546/standings">Положение</a></li> <li><a href="/contest/1546/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_37a94b7c6f26dc591923f90e006e3e5f2d7e4630"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. AquaMoon и перестановки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Cirno подготовила $$$n$$$ массивов длины $$$n$$$ каждый. Каждый массив — это перестановка из $$$n$$$ целых чисел от $$$1$$$ до $$$n$$$. Эти массивы специальные: для всех $$$1 \leq i \leq n$$$, если мы возьмем $$$i$$$-й элемент каждого массива и построим другой массив длины $$$n$$$, состоящий из этих элементов, получившийся массив также будет перестановкой $$$n$$$ чисел от $$$1$$$ до $$$n$$$. Другими словами, если эти $$$n$$$ массивов расположить друг под другом, образовав матрицу с $$$n$$$ строками и $$$n$$$ столбцами, эта матрица будет <a href="https://ru.wikipedia.org/wiki/Латинский_квадрат">латинским квадратом</a>.</p><p>После этого Cirno добавила дополнительные $$$n$$$ массивов, каждый массив также является перестановкой из $$$n$$$ целых чисел от $$$1$$$ до $$$n$$$. Для всех $$$1 \leq i \leq n$$$ существует <span class="tex-font-style-bf">хотя бы одна</span> позиция $$$1 \leq k \leq n$$$, такая что для $$$i$$$-го и $$$(n + i)$$$-го массивов $$$k$$$-е элементы совпадают. Обратите внимание, что массивы с индексами от $$$n + 1$$$ до $$$2n$$$ <span class="tex-font-style-bf">не обязаны</span> образовывать латинский квадрат.</p><p>Также Cirno убедилась, что среди $$$2n$$$ массивов никакие два не равны, то есть для всех пар индексов $$$1 \leq i &lt; j \leq 2n$$$ существует <span class="tex-font-style-bf">хотя бы одна</span> позиция $$$1 \leq k \leq n$$$, такая что в $$$i$$$-м и $$$j$$$-м массивах $$$k$$$-е элементы <span class="tex-font-style-bf">различны</span>.</p><p>В конце Cirno произвольно поменяла порядок, в котором расположены подготовленные $$$2n$$$ массивов.</p><p>AquaMoon называет подмножество всех $$$2n$$$ массивов размера $$$n$$$ <span class="tex-font-style-bf">хорошим</span>, если эти массивы образуют латинский квадрат.</p><p>AquaMoon хочет узнать, сколько хороших подмножеств существует. Поскольку это количество может быть очень большим, найдите его по модулю $$$998\,244\,353$$$. Также она хочет найти любое хорошее подмножество. Можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$5 \leq n \leq 500$$$).</p><p>Затем $$$2n$$$ строк следует. $$$i$$$-я из этих строк содержит $$$n$$$ целых чисел, составляющих $$$i$$$-й массив.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$500$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите две строки.</p><p>В первой строке выведите количество хороших подмножеств по модулю $$$998\,244\,353$$$.</p><p>Во второй строке выведите $$$n$$$ индексов от $$$1$$$ до $$$2n$$$ — индексы $$$n$$$ массивов, которые образуют хорошее подмножество (вы можете вывести их в любом порядке). Если существует несколько возможных ответов — выведите любой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 7 1 2 3 4 5 6 7 2 3 4 5 6 7 1 3 4 5 6 7 1 2 4 5 6 7 1 2 3 5 6 7 1 2 3 4 6 7 1 2 3 4 5 7 1 2 3 4 5 6 1 2 3 4 5 7 6 1 3 4 5 6 7 2 1 4 5 6 7 3 2 1 5 6 7 4 2 3 1 6 7 5 2 3 4 1 7 6 2 3 4 5 1 7 2 3 4 5 6 5 4 5 1 2 3 3 5 2 4 1 1 2 3 4 5 5 2 4 1 3 3 4 5 1 2 2 3 4 5 1 1 3 5 2 4 4 1 3 5 2 2 4 1 3 5 5 1 2 3 4 6 2 3 4 5 6 1 3 1 2 6 4 5 6 1 2 3 4 5 5 6 1 3 2 4 4 3 6 5 2 1 5 6 1 2 3 4 4 5 6 1 2 3 3 4 5 6 1 2 1 2 3 4 5 6 2 5 4 1 6 3 3 2 5 4 1 6 1 4 3 6 5 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 2 3 4 5 6 7 2 1 3 5 6 10 4 1 3 6 7 8 9 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных количество хороших подмножеств равно $$$1$$$. Единственное такое подмножество это подмножество массивов с индексами $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, $$$6$$$, $$$7$$$.</p><p>Во втором наборе входных данных количество хороших подмножеств равно $$$2$$$. Эти подмножества это $$$1$$$, $$$3$$$, $$$5$$$, $$$6$$$, $$$10$$$, а также $$$2$$$, $$$4$$$, $$$7$$$, $$$8$$$, $$$9$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c82d1f367b73',t:'MTY5NjY2NzQyNC44ODEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "*2800"]
1546F
1546
F
ru
F. AquaMoon и неправильная координата
<div class="problem-statement"><div class="header"><div class="title">F. AquaMoon и неправильная координата</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Cirno дала AquaMoon задачу. Есть $$$m$$$ человек, пронумерованных целыми числами от $$$0$$$ до $$$m - 1$$$. Они стоят на координатной прямой в точках с положительными целочисленными координатами. Они смотрят в направлении увеличения координат.</p><p>В этот момент все начинают бежать с фиксированной скоростью в направлении увеличения координат. Изначальная координата $$$i$$$-о человека на прямой это $$$x_i$$$, а скорость $$$i$$$-о человека это $$$v_i$$$. Поэтому координата $$$i$$$-о человека в момент времени $$$t$$$ будет $$$x_i + t \cdot v_i$$$.</p><p>Cirno запомнила координаты всех $$$m$$$ человек в $$$k$$$ последовательных целочисленных моментах времени от $$$0$$$ до $$$k - 1$$$. В каждый момент координаты всех $$$m$$$ человек были запомнены в <span class="tex-font-style-bf">произвольном порядке</span>.</p><p>Чтобы сделать задачу более веселой, Cirno изменила одну из координат в момент времени $$$y$$$ ($$$0 &lt; y &lt; k-1$$$) на <span class="tex-font-style-bf">другое</span> целое число.</p><p>AquaMoon хочет найти момент времени $$$y$$$ и изначальную координату $$$p$$$ перед изменением. К сожалению, она совсем не программист. Поэтому она не смогла решить эту задачу. Можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p><span class="tex-font-style-bf">Эта задача сделана как интерактивная. Это означает, что ваше решение будет считывать входные данные, которые вывел интерактор. Однако, интерактор выведет полные входные данные в начале, и после этого вы должны будете вывести ответ. Поэтому вы должны решать задачу так, как если бы вы решали обычную, не интерактивную задачу, потому что у вас не будет никакого процесса взаимодействия. Единственная вещь, про которую вы не должны забыть — это сбросить буфер выходного потока после вывода ответа. Иначе ваше решение может получить вердикт «Решение «зависло»». Обратитесь к <a href="https://codeforces.com/blog/entry/45307">руководству по интерактивным задачам</a> для более детальной информации про сброс буфера выходного потока.</span></p><p>В первой строке находится два целых числа $$$m$$$ и $$$k$$$ ($$$5 \leq m \leq 1000$$$, $$$7 \leq k \leq 1000$$$) — количество человек и количество запомненных моментов.</p><p>Следующие $$$k$$$ строк содержат запомненные координаты. $$$i$$$-я из этих строк содержит $$$m$$$ целых чисел от $$$1$$$ до $$$10^6$$$ (включительно), обозначающих координаты, которые запомнила Cirno в момент времени $$$i-1$$$.</p><p>Гарантируется, что входные данные валидные (то есть только одно целое число было изменено на другое в соответствии с условием задачи). Также гарантируется, что $$$1 \le v_i \le 1000$$$ для всех $$$1 \leq i \leq m$$$.</p><p><span class="tex-font-style-bf">Формат теста для взлома</span>:</p><p>В первой строке должно находиться два целых числа $$$m$$$ и $$$k$$$ ($$$5 \leq m \leq 1000$$$, $$$7 \leq k \leq 1000$$$) — количество человек и количество запомненных моментов.</p><p>Во второй строке должно находиться $$$m$$$ целых чисел $$$x_0, x_1, \dots,x_{m - 1}$$$ ($$$1 \le x_i \le 10^6$$$), где $$$x_i$$$ это изначальная координата $$$i$$$-о человека.</p><p>В третьей строке должно находиться $$$m$$$ целых чисел $$$v_0, v_1, \dots,v_{m - 1}$$$ ($$$1 \le v_i \le 1000$$$), где $$$v_i$$$ это скорость $$$i$$$-о человека. Должно быть выполнено, что $$$x_i + (k-1) v_i \leq 10^6$$$ для всех $$$0 \leq i &lt; m$$$.</p><p>Каждая из следующих $$$k$$$ строк должна содержать $$$m$$$ целых чисел. $$$i$$$-я строка должна содержать $$$m$$$ различных целых чисел $$$p_0, p_1, \ldots, p_{m-1}$$$ ($$$0 \leq p_j &lt; m$$$). Их значение: $$$j$$$-е целое число во входных данных в момент времени $$$i$$$ это координата человека $$$p_{j}$$$.</p><p>В последней строке должно находиться три целых числа $$$y$$$, $$$i$$$, $$$c$$$. Cirno поменяла координату $$$i$$$-о человека в момент времени $$$y$$$ на $$$c$$$ ($$$1 \leq y \leq k-2$$$, $$$0 \leq i \leq m - 1$$$, $$$1 \leq c \leq 10^6$$$, $$$c \neq x_i + y \cdot v_i$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственную строку с двумя целыми числами $$$y$$$, $$$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 6 9 9 6 9 10 7 10 8 10 11 11 11 10 8 12 12 12 12 9 14 13 12 10 13 11 14 16 14 14 12 15 18 15 15 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 13 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте изначальные координаты людей это $$$9$$$, $$$6$$$, $$$6$$$, $$$9$$$, $$$9$$$ и их скорости это $$$1$$$, $$$2$$$, $$$1$$$, $$$1$$$, $$$1$$$. Поэтому несложно заметить, что в момент времени $$$4$$$ одна координата была изменена c $$$13$$$ на $$$12$$$.</p><p>Это первый тест, записанный в формате для взломов:</p><pre class="verbatim"><br/>5 7<br/>9 6 6 9 9<br/>1 2 1 1 1<br/>2 3 4 1 0<br/>0 2 3 1 4<br/>4 3 0 1 2<br/>1 3 4 0 2<br/>1 4 0 2 3<br/>2 4 1 3 0<br/>2 4 1 3 0<br/>4 0 12<br/></pre></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="4bed23785f3d3751c3e30aed9342046a"/> <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="45cb11cb46147787c541139a8ab89dca9f0eaa38"/> <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='4bed23785f3d3751c3e30aed9342046a'>&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%2F1546%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='4bed23785f3d3751c3e30aed9342046a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1546">Codeforces Round 732 (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='4bed23785f3d3751c3e30aed9342046a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1546/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='4bed23785f3d3751c3e30aed9342046a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1042729"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4bed23785f3d3751c3e30aed9342046a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1042729"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92482" title="Codeforces Round #732" target="_blank">Codeforces Round #732 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13991" resourceName="Codeforces Round #732" resourceManual="true" src="//codeforces.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/92739" title="Codeforces Round #732 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13997" resourceName="Codeforces Round #732 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/1546">Задачи</a></li> <li><a href="/contest/1546/submit">Отослать</a></li> <li><a href="/contest/1546/my">Мои посылки</a></li> <li><a href="/contest/1546/status">Статус</a></li> <li><a href="/contest/1546/hacks">Взломы</a></li> <li><a href="/contest/1546/room/1">Комната</a></li> <li><a href="/contest/1546/standings">Положение</a></li> <li><a href="/contest/1546/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_ae72f1ad9e2f1b1f9b5f41b4831541d0e755b105"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. AquaMoon и неправильная координата</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Cirno дала AquaMoon задачу. Есть $$$m$$$ человек, пронумерованных целыми числами от $$$0$$$ до $$$m - 1$$$. Они стоят на координатной прямой в точках с положительными целочисленными координатами. Они смотрят в направлении увеличения координат.</p><p>В этот момент все начинают бежать с фиксированной скоростью в направлении увеличения координат. Изначальная координата $$$i$$$-о человека на прямой это $$$x_i$$$, а скорость $$$i$$$-о человека это $$$v_i$$$. Поэтому координата $$$i$$$-о человека в момент времени $$$t$$$ будет $$$x_i + t \cdot v_i$$$.</p><p>Cirno запомнила координаты всех $$$m$$$ человек в $$$k$$$ последовательных целочисленных моментах времени от $$$0$$$ до $$$k - 1$$$. В каждый момент координаты всех $$$m$$$ человек были запомнены в <span class="tex-font-style-bf">произвольном порядке</span>.</p><p>Чтобы сделать задачу более веселой, Cirno изменила одну из координат в момент времени $$$y$$$ ($$$0 &lt; y &lt; k-1$$$) на <span class="tex-font-style-bf">другое</span> целое число.</p><p>AquaMoon хочет найти момент времени $$$y$$$ и изначальную координату $$$p$$$ перед изменением. К сожалению, она совсем не программист. Поэтому она не смогла решить эту задачу. Можете ли вы помочь ей?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p><span class="tex-font-style-bf">Эта задача сделана как интерактивная. Это означает, что ваше решение будет считывать входные данные, которые вывел интерактор. Однако, интерактор выведет полные входные данные в начале, и после этого вы должны будете вывести ответ. Поэтому вы должны решать задачу так, как если бы вы решали обычную, не интерактивную задачу, потому что у вас не будет никакого процесса взаимодействия. Единственная вещь, про которую вы не должны забыть — это сбросить буфер выходного потока после вывода ответа. Иначе ваше решение может получить вердикт «Решение «зависло»». Обратитесь к <a href="https://codeforces.com/blog/entry/45307">руководству по интерактивным задачам</a> для более детальной информации про сброс буфера выходного потока.</span></p><p>В первой строке находится два целых числа $$$m$$$ и $$$k$$$ ($$$5 \leq m \leq 1000$$$, $$$7 \leq k \leq 1000$$$) — количество человек и количество запомненных моментов.</p><p>Следующие $$$k$$$ строк содержат запомненные координаты. $$$i$$$-я из этих строк содержит $$$m$$$ целых чисел от $$$1$$$ до $$$10^6$$$ (включительно), обозначающих координаты, которые запомнила Cirno в момент времени $$$i-1$$$.</p><p>Гарантируется, что входные данные валидные (то есть только одно целое число было изменено на другое в соответствии с условием задачи). Также гарантируется, что $$$1 \le v_i \le 1000$$$ для всех $$$1 \leq i \leq m$$$.</p><p><span class="tex-font-style-bf">Формат теста для взлома</span>:</p><p>В первой строке должно находиться два целых числа $$$m$$$ и $$$k$$$ ($$$5 \leq m \leq 1000$$$, $$$7 \leq k \leq 1000$$$) — количество человек и количество запомненных моментов.</p><p>Во второй строке должно находиться $$$m$$$ целых чисел $$$x_0, x_1, \dots,x_{m - 1}$$$ ($$$1 \le x_i \le 10^6$$$), где $$$x_i$$$ это изначальная координата $$$i$$$-о человека.</p><p>В третьей строке должно находиться $$$m$$$ целых чисел $$$v_0, v_1, \dots,v_{m - 1}$$$ ($$$1 \le v_i \le 1000$$$), где $$$v_i$$$ это скорость $$$i$$$-о человека. Должно быть выполнено, что $$$x_i + (k-1) v_i \leq 10^6$$$ для всех $$$0 \leq i &lt; m$$$.</p><p>Каждая из следующих $$$k$$$ строк должна содержать $$$m$$$ целых чисел. $$$i$$$-я строка должна содержать $$$m$$$ различных целых чисел $$$p_0, p_1, \ldots, p_{m-1}$$$ ($$$0 \leq p_j &lt; m$$$). Их значение: $$$j$$$-е целое число во входных данных в момент времени $$$i$$$ это координата человека $$$p_{j}$$$.</p><p>В последней строке должно находиться три целых числа $$$y$$$, $$$i$$$, $$$c$$$. Cirno поменяла координату $$$i$$$-о человека в момент времени $$$y$$$ на $$$c$$$ ($$$1 \leq y \leq k-2$$$, $$$0 \leq i \leq m - 1$$$, $$$1 \leq c \leq 10^6$$$, $$$c \neq x_i + y \cdot v_i$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственную строку с двумя целыми числами $$$y$$$, $$$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 6 9 9 6 9 10 7 10 8 10 11 11 11 10 8 12 12 12 12 9 14 13 12 10 13 11 14 16 14 14 12 15 18 15 15 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 13 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте изначальные координаты людей это $$$9$$$, $$$6$$$, $$$6$$$, $$$9$$$, $$$9$$$ и их скорости это $$$1$$$, $$$2$$$, $$$1$$$, $$$1$$$, $$$1$$$. Поэтому несложно заметить, что в момент времени $$$4$$$ одна координата была изменена c $$$13$$$ на $$$12$$$.</p><p>Это первый тест, записанный в формате для взломов:</p><pre class="verbatim"><br />5 7<br />9 6 6 9 9<br />1 2 1 1 1<br />2 3 4 1 0<br />0 2 3 1 4<br />4 3 0 1 2<br />1 3 4 0 2<br />1 4 0 2 3<br />2 4 1 3 0<br />2 4 1 3 0<br />4 0 12<br /></pre></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c83528689d63',t:'MTY5NjY2NzQyNi4xNzQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*3000"]
1547A
1547
A
ru
A. Кратчайший путь с препятствием
<div class="problem-statement"><div class="header"><div class="title">A. Кратчайший путь с препятствием</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>На бесконечном клетчатом поле отмечены три различные клетки: $$$A$$$, $$$B$$$ и $$$F$$$. Выведите длину кратчайшего пути из $$$A$$$ в $$$B$$$, если:</p><ul> <li> за один ход можно переходить на любую из четырех соседних по стороне клеток; </li><li> посещать клетку $$$F$$$ — запрещено (она является препятствием). </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее следуют описания $$$t$$$ наборов входных данных, перед каждым из них входные данные содержат пустую строку.</p><p>Каждый набор входных данных состоит из трех строк. Первая из них содержит два целых числа $$$x_A, y_A$$$ ($$$1 \le x_A, y_A \le 1000$$$) — координаты стартовой клетки $$$A$$$. Вторая из них содержит два целых числа $$$x_B, y_B$$$ ($$$1 \le x_B, y_B \le 1000$$$) — координаты конечной клетки $$$B$$$. Третья строка содержит два целых числа $$$x_F, y_F$$$ ($$$1 \le x_F, y_F \le 1000$$$) — координаты клетки $$$F$$$, которая является препятствием. Все три клетки — различны.</p><p>Координата $$$x$$$ соответствует номеру столбца, а $$$y$$$ — номеру строки (см. картинки ниже).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк. $$$i$$$-я из них должна содержать ответ для $$$i$$$-го набора входных данных — длину кратчайшего пути из клетки $$$A$$$ в клетку $$$B$$$, если клетка $$$F$$$ запрещена для посещения.</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 3 3 2 2 2 5 2 1 2 3 1000 42 1000 1 1000 1000 1 10 3 10 2 10 3 8 7 8 3 7 2 1 4 1 1 1 1 344 1 10 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 6 41 4 4 2 334 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><center> <img class="tex-graphics" src="https://espresso.codeforces.com/7ae35ac95bfa8dca03718af8fb127e31d040979f.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-size-small">Пример возможного кратчайшего пути для первого набора входных данных.</span> </center><center> <img class="tex-graphics" src="https://espresso.codeforces.com/7294b2a6be8ca29936c63a85e1fd4c7a915113b6.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-size-small">Пример возможного кратчайшего пути для второго набора входных данных.</span> </center></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="dec2f76b422f32a8448bfd96d19dfa70"/> <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="578290d168a7daa6108dcfc3ded930345ad3b1ed"/> <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='dec2f76b422f32a8448bfd96d19dfa70'>&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%2F1547%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='dec2f76b422f32a8448bfd96d19dfa70'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1547">Codeforces Round 731 (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='dec2f76b422f32a8448bfd96d19dfa70'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1547/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *800 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='dec2f76b422f32a8448bfd96d19dfa70'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1041925"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='dec2f76b422f32a8448bfd96d19dfa70'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1041925"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92681" title="Codeforces Round #731 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13992:13993" 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/92715" title="Разбор задач Codeforces Round #731 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13994:13995" 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/1547">Задачи</a></li> <li><a href="/contest/1547/submit">Отослать</a></li> <li><a href="/contest/1547/my">Мои посылки</a></li> <li><a href="/contest/1547/status">Статус</a></li> <li><a href="/contest/1547/hacks">Взломы</a></li> <li><a href="/contest/1547/standings">Положение</a></li> <li><a href="/contest/1547/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c342499f98aeb5d948b380f6caa181ff8d6e0019"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>На бесконечном клетчатом поле отмечены три различные клетки: $$$A$$$, $$$B$$$ и $$$F$$$. Выведите длину кратчайшего пути из $$$A$$$ в $$$B$$$, если:</p><ul> <li> за один ход можно переходить на любую из четырех соседних по стороне клеток; </li><li> посещать клетку $$$F$$$ — запрещено (она является препятствием). </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее следуют описания $$$t$$$ наборов входных данных, перед каждым из них входные данные содержат пустую строку.</p><p>Каждый набор входных данных состоит из трех строк. Первая из них содержит два целых числа $$$x_A, y_A$$$ ($$$1 \le x_A, y_A \le 1000$$$) — координаты стартовой клетки $$$A$$$. Вторая из них содержит два целых числа $$$x_B, y_B$$$ ($$$1 \le x_B, y_B \le 1000$$$) — координаты конечной клетки $$$B$$$. Третья строка содержит два целых числа $$$x_F, y_F$$$ ($$$1 \le x_F, y_F \le 1000$$$) — координаты клетки $$$F$$$, которая является препятствием. Все три клетки — различны.</p><p>Координата $$$x$$$ соответствует номеру столбца, а $$$y$$$ — номеру строки (см. картинки ниже).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк. $$$i$$$-я из них должна содержать ответ для $$$i$$$-го набора входных данных — длину кратчайшего пути из клетки $$$A$$$ в клетку $$$B$$$, если клетка $$$F$$$ запрещена для посещения.</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 3 3 2 2 2 5 2 1 2 3 1000 42 1000 1 1000 1000 1 10 3 10 2 10 3 8 7 8 3 7 2 1 4 1 1 1 1 344 1 10 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 6 41 4 4 2 334 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><center> <img class="tex-graphics" src="https://espresso.codeforces.com/7ae35ac95bfa8dca03718af8fb127e31d040979f.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-size-small">Пример возможного кратчайшего пути для первого набора входных данных.</span> </center><center> <img class="tex-graphics" src="https://espresso.codeforces.com/7294b2a6be8ca29936c63a85e1fd4c7a915113b6.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-size-small">Пример возможного кратчайшего пути для второго набора входных данных.</span> </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c83d5eff16db',t:'MTY5NjY2NzQyNy41OTEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*800"]
1547B
1547
B
ru
B. Алфавитные строки
<div class="problem-statement"><div class="header"><div class="title">B. Алфавитные строки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Строка $$$s$$$ длины $$$n$$$ ($$$1 \le n \le 26$$$) называется <span class="tex-font-style-it">алфавитной</span>, если она может быть получена с помощью следующего алгоритма:</p><ul> <li> вначале записываем в $$$s$$$ пустую строку (то есть выполняем присваивание $$$s$$$ <span class="tex-font-style-tt">:= ""</span>); </li><li> далее выполним следующий шаг $$$n$$$ раз; </li><li> при $$$i$$$-м выполнении шага берем $$$i$$$-ю строчную букву латинского алфавита и приписываем её либо слева к строке $$$s$$$, либо справа к строке $$$s$$$ (то есть осуществляем присвоение $$$s$$$ <span class="tex-font-style-tt">:=</span> $$$c+s$$$ или $$$s$$$ <span class="tex-font-style-tt">:=</span> $$$s+c$$$, где $$$c$$$ — $$$i$$$-я буква латинского алфавита). </li></ul><p>Иными словами, переберем $$$n$$$ первых букв латинского алфавита от '<span class="tex-font-style-tt">a</span>' и далее. Каждый раз к строке $$$s$$$ будем приписывать букву либо слева, либо справа. Строки, которые можно получить таким образом — алфавитные.</p><p>Например, следующие строки являются алфавитными: «<span class="tex-font-style-tt">a</span>», «<span class="tex-font-style-tt">ba</span>», «<span class="tex-font-style-tt">ab</span>», «<span class="tex-font-style-tt">bac</span>» и «<span class="tex-font-style-tt">ihfcbadeg</span>». Следующие строки <span class="tex-font-style-bf">не являются</span> алфавитными: «<span class="tex-font-style-tt">z</span>», «<span class="tex-font-style-tt">aa</span>», «<span class="tex-font-style-tt">ca</span>», «<span class="tex-font-style-tt">acb</span>», «<span class="tex-font-style-tt">xyz</span>» и «<span class="tex-font-style-tt">ddcba</span>».</p><p>По заданной строке определите, является ли она алфавитной.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор входных данных записан в отдельной строке, которая содержит $$$s$$$. Строка $$$s$$$ состоит из строчных букв латинского алфавита, имеет длину от $$$1$$$ до $$$26$$$, включительно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк, каждая из строк должна содержать ответ на соответствующий набор входных данных. Выведите <span class="tex-font-style-tt">YES</span>, если заданная строка $$$s$$$ является алфавитной и <span class="tex-font-style-tt">NO</span> в противном случае.</p><p>Вы можете выводить <span class="tex-font-style-tt">YES</span> и <span class="tex-font-style-tt">NO</span> в любом регистре (например, строки <span class="tex-font-style-tt">yEs</span>, <span class="tex-font-style-tt">yes</span>, <span class="tex-font-style-tt">Yes</span> и <span class="tex-font-style-tt">YES</span> будут распознаны как положительный ответ).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 11 a ba ab bac ihfcbadeg z aa ca acb xyz ddcba </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES YES YES YES NO NO NO NO NO NO </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="48646fb940888fbd8ee69aa8c101e8ab"/> <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="578290d168a7daa6108dcfc3ded930345ad3b1ed"/> <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='48646fb940888fbd8ee69aa8c101e8ab'>&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%2F1547%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='48646fb940888fbd8ee69aa8c101e8ab'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1547">Codeforces Round 731 (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='48646fb940888fbd8ee69aa8c101e8ab'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1547/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='48646fb940888fbd8ee69aa8c101e8ab'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1041926"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='48646fb940888fbd8ee69aa8c101e8ab'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1041926"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92681" title="Codeforces Round #731 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13992:13993" 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/92715" title="Разбор задач Codeforces Round #731 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13994:13995" 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/1547">Задачи</a></li> <li><a href="/contest/1547/submit">Отослать</a></li> <li><a href="/contest/1547/my">Мои посылки</a></li> <li><a href="/contest/1547/status">Статус</a></li> <li><a href="/contest/1547/hacks">Взломы</a></li> <li><a href="/contest/1547/standings">Положение</a></li> <li><a href="/contest/1547/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9ac8b0734517301e9a5f490765b270a665733de5"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>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$$$ длины $$$n$$$ ($$$1 \le n \le 26$$$) называется <span class="tex-font-style-it">алфавитной</span>, если она может быть получена с помощью следующего алгоритма:</p><ul> <li> вначале записываем в $$$s$$$ пустую строку (то есть выполняем присваивание $$$s$$$ <span class="tex-font-style-tt">:= &quot;&quot;</span>); </li><li> далее выполним следующий шаг $$$n$$$ раз; </li><li> при $$$i$$$-м выполнении шага берем $$$i$$$-ю строчную букву латинского алфавита и приписываем её либо слева к строке $$$s$$$, либо справа к строке $$$s$$$ (то есть осуществляем присвоение $$$s$$$ <span class="tex-font-style-tt">:=</span> $$$c+s$$$ или $$$s$$$ <span class="tex-font-style-tt">:=</span> $$$s+c$$$, где $$$c$$$ — $$$i$$$-я буква латинского алфавита). </li></ul><p>Иными словами, переберем $$$n$$$ первых букв латинского алфавита от '<span class="tex-font-style-tt">a</span>' и далее. Каждый раз к строке $$$s$$$ будем приписывать букву либо слева, либо справа. Строки, которые можно получить таким образом — алфавитные.</p><p>Например, следующие строки являются алфавитными: «<span class="tex-font-style-tt">a</span>», «<span class="tex-font-style-tt">ba</span>», «<span class="tex-font-style-tt">ab</span>», «<span class="tex-font-style-tt">bac</span>» и «<span class="tex-font-style-tt">ihfcbadeg</span>». Следующие строки <span class="tex-font-style-bf">не являются</span> алфавитными: «<span class="tex-font-style-tt">z</span>», «<span class="tex-font-style-tt">aa</span>», «<span class="tex-font-style-tt">ca</span>», «<span class="tex-font-style-tt">acb</span>», «<span class="tex-font-style-tt">xyz</span>» и «<span class="tex-font-style-tt">ddcba</span>».</p><p>По заданной строке определите, является ли она алфавитной.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор входных данных записан в отдельной строке, которая содержит $$$s$$$. Строка $$$s$$$ состоит из строчных букв латинского алфавита, имеет длину от $$$1$$$ до $$$26$$$, включительно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк, каждая из строк должна содержать ответ на соответствующий набор входных данных. Выведите <span class="tex-font-style-tt">YES</span>, если заданная строка $$$s$$$ является алфавитной и <span class="tex-font-style-tt">NO</span> в противном случае.</p><p>Вы можете выводить <span class="tex-font-style-tt">YES</span> и <span class="tex-font-style-tt">NO</span> в любом регистре (например, строки <span class="tex-font-style-tt">yEs</span>, <span class="tex-font-style-tt">yes</span>, <span class="tex-font-style-tt">Yes</span> и <span class="tex-font-style-tt">YES</span> будут распознаны как положительный ответ).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 11 a ba ab bac ihfcbadeg z aa ca acb xyz ddcba </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES YES YES YES NO NO NO NO NO NO </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Пример содержит наборы входных данных из основной части условия.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c8461aea9d43',t:'MTY5NjY2NzQyOC45NzcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u043e\u043a\u0438", "*800"]
1547C
1547
C
ru
C. Парное программирование
<div class="problem-statement"><div class="header"><div class="title">C. Парное программирование</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Монокарп и Поликарп изучают новые приемы программирования. Сейчас они решили попробовать парное программирование.</p><p>Известно, что они проработали вместе $$$n + m$$$ минут, работая над одним файлом. Каждую минуту ровно один из них делал одно изменение в файле. До начала их работы в файле было $$$k$$$ строк.</p><p>За одну минуту любой из них может выполнить одно из двух действий: добавить новую строку в конец файла или изменить одну его строку.</p><p>Суммарно Монокарп работал $$$n$$$ минут и выполнил последовательность действий $$$[a_1, a_2, \dots, a_n]$$$, где $$$a_i = 0$$$, если он добавил новую строку в конец файла или $$$a_i &gt; 0$$$, если он изменил строку с номером $$$a_i$$$. Действия Монокарп производил именно в таком порядке: сначала $$$a_1$$$, затем $$$a_2$$$ и так далее до $$$a_n$$$.</p><p>Суммарно Поликарп работал $$$m$$$ минут и выполнил последовательность действий $$$[b_1, b_2, \dots, b_m]$$$, где $$$b_j = 0$$$, если он добавил новую строку в конец файла или $$$b_j &gt; 0$$$, если он изменил строку с номером $$$b_j$$$. Действия Поликарп производил именно в таком порядке: сначала $$$b_1$$$, затем $$$b_2$$$ и так далее до $$$b_m$$$.</p><p>Восстановите их общую последовательность действий длины $$$n + m$$$, такую, в которой все действия были бы корректными — то есть не должно быть изменений еще не существующих строк. Имейте в виду, что в общей последовательности действия Монокарпа должны образовывать подпоследовательность $$$[a_1, a_2, \dots, a_n]$$$, а Поликарпа — подпоследовательность $$$[b_1, b_2, \dots, b_m]$$$. Монокарп и Поликарп могут сменять друг друга за компьютером произвольное количество раз.</p><p>Рассмотрим пример. Пусть изначально $$$k = 3$$$. Монокарп сначала изменил строку с номером $$$2$$$, а затем добавил новую строку (то есть $$$n = 2, \: a = [2, 0]$$$). Поликарп же сначала добавил новую строку, а затем изменил строку с номером $$$5$$$ (то есть $$$m = 2, \: b = [0, 5]$$$).</p><p>Так как изначальная длина файла равна $$$3$$$, для того, чтобы Поликарп смог изменить строку с номером $$$5$$$, необходимо сначала добавить две новые строки. Примером правильных последовательностей изменений в таком случае будет $$$[0, 2, 0, 5]$$$ или $$$[2, 0, 0, 5]$$$. Последовательности изменений $$$[0, 0, 5, 2]$$$ (нарушен порядок действий) и $$$[0, 5, 2, 0]$$$ (нельзя отредактировать строку $$$5$$$) не являются корректными.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных в тесте. Далее следуют $$$t$$$ наборов входных данных. Перед каждым набором входных данных записана пустая строка.</p><p>Каждый набор входных данных состоит из трех строк. В первой строке задано три целых числа $$$k$$$, $$$n$$$, $$$m$$$ ($$$0 \le k \le 100$$$, $$$1 \le n, m \le 100$$$) — изначальное количество строк в файле и длины массивов изменений Монокарпа и Поликарпа соответственно.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 300$$$).</p><p>Третья строка содержит $$$m$$$ целых чисел $$$b_1, b_2, \dots, b_m$$$ ($$$0 \le b_j \le 300$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите через пробел элементы любой корректной объединенной последовательности действий Монокарпа и Поликарпа длины $$$n + m$$$ или <span class="tex-font-style-tt">-1</span>, если такой последовательности не существует.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 3 2 2 2 0 0 5 4 3 2 2 0 5 0 6 0 2 2 1 0 2 3 5 4 4 6 0 8 0 0 7 0 9 5 4 1 8 7 8 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 0 0 5 0 2 0 6 5 -1 0 6 0 7 0 8 0 9 -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="a8165a8dec00e88c58f9cbdac3401b35"/> <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="578290d168a7daa6108dcfc3ded930345ad3b1ed"/> <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='a8165a8dec00e88c58f9cbdac3401b35'>&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%2F1547%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='a8165a8dec00e88c58f9cbdac3401b35'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1547">Codeforces Round 731 (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='a8165a8dec00e88c58f9cbdac3401b35'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1547/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='a8165a8dec00e88c58f9cbdac3401b35'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1041927"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a8165a8dec00e88c58f9cbdac3401b35'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1041927"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92681" title="Codeforces Round #731 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13992:13993" 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/92715" title="Разбор задач Codeforces Round #731 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13994:13995" 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/1547">Задачи</a></li> <li><a href="/contest/1547/submit">Отослать</a></li> <li><a href="/contest/1547/my">Мои посылки</a></li> <li><a href="/contest/1547/status">Статус</a></li> <li><a href="/contest/1547/hacks">Взломы</a></li> <li><a href="/contest/1547/standings">Положение</a></li> <li><a href="/contest/1547/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9d787fc19e5693d18f0219c51249358800ddee89"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>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 + m$$$ минут, работая над одним файлом. Каждую минуту ровно один из них делал одно изменение в файле. До начала их работы в файле было $$$k$$$ строк.</p><p>За одну минуту любой из них может выполнить одно из двух действий: добавить новую строку в конец файла или изменить одну его строку.</p><p>Суммарно Монокарп работал $$$n$$$ минут и выполнил последовательность действий $$$[a_1, a_2, \dots, a_n]$$$, где $$$a_i = 0$$$, если он добавил новую строку в конец файла или $$$a_i &gt; 0$$$, если он изменил строку с номером $$$a_i$$$. Действия Монокарп производил именно в таком порядке: сначала $$$a_1$$$, затем $$$a_2$$$ и так далее до $$$a_n$$$.</p><p>Суммарно Поликарп работал $$$m$$$ минут и выполнил последовательность действий $$$[b_1, b_2, \dots, b_m]$$$, где $$$b_j = 0$$$, если он добавил новую строку в конец файла или $$$b_j &gt; 0$$$, если он изменил строку с номером $$$b_j$$$. Действия Поликарп производил именно в таком порядке: сначала $$$b_1$$$, затем $$$b_2$$$ и так далее до $$$b_m$$$.</p><p>Восстановите их общую последовательность действий длины $$$n + m$$$, такую, в которой все действия были бы корректными — то есть не должно быть изменений еще не существующих строк. Имейте в виду, что в общей последовательности действия Монокарпа должны образовывать подпоследовательность $$$[a_1, a_2, \dots, a_n]$$$, а Поликарпа — подпоследовательность $$$[b_1, b_2, \dots, b_m]$$$. Монокарп и Поликарп могут сменять друг друга за компьютером произвольное количество раз.</p><p>Рассмотрим пример. Пусть изначально $$$k = 3$$$. Монокарп сначала изменил строку с номером $$$2$$$, а затем добавил новую строку (то есть $$$n = 2, \: a = [2, 0]$$$). Поликарп же сначала добавил новую строку, а затем изменил строку с номером $$$5$$$ (то есть $$$m = 2, \: b = [0, 5]$$$).</p><p>Так как изначальная длина файла равна $$$3$$$, для того, чтобы Поликарп смог изменить строку с номером $$$5$$$, необходимо сначала добавить две новые строки. Примером правильных последовательностей изменений в таком случае будет $$$[0, 2, 0, 5]$$$ или $$$[2, 0, 0, 5]$$$. Последовательности изменений $$$[0, 0, 5, 2]$$$ (нарушен порядок действий) и $$$[0, 5, 2, 0]$$$ (нельзя отредактировать строку $$$5$$$) не являются корректными.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных в тесте. Далее следуют $$$t$$$ наборов входных данных. Перед каждым набором входных данных записана пустая строка.</p><p>Каждый набор входных данных состоит из трех строк. В первой строке задано три целых числа $$$k$$$, $$$n$$$, $$$m$$$ ($$$0 \le k \le 100$$$, $$$1 \le n, m \le 100$$$) — изначальное количество строк в файле и длины массивов изменений Монокарпа и Поликарпа соответственно.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 300$$$).</p><p>Третья строка содержит $$$m$$$ целых чисел $$$b_1, b_2, \dots, b_m$$$ ($$$0 \le b_j \le 300$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите через пробел элементы любой корректной объединенной последовательности действий Монокарпа и Поликарпа длины $$$n + m$$$ или <span class="tex-font-style-tt">-1</span>, если такой последовательности не существует.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 3 2 2 2 0 0 5 4 3 2 2 0 5 0 6 0 2 2 1 0 2 3 5 4 4 6 0 8 0 0 7 0 9 5 4 1 8 7 8 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 0 0 5 0 2 0 6 5 -1 0 6 0 7 0 8 0 9 -1 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c84eca1f0058',t:'MTY5NjY2NzQzMC4zNzcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "*1100"]
1547D
1547
D
ru
D. Взаимнорастущая последовательность
<div class="problem-statement"><div class="header"><div class="title">D. Взаимнорастущая последовательность</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Последовательность неотрицательных целых чисел $$$a_1, a_2, \dots, a_n$$$ называется <span class="tex-font-style-it">растущей</span>, если для всех $$$i$$$ от $$$1$$$ до $$$n - 1$$$ в двоичной записи $$$a_i$$$ все единичные биты стоят на местах битов, которые тоже единичные, в двоичной записи $$$a_{i + 1}$$$ (иными словами, $$$a_i \:\&amp;\: a_{i + 1} = a_i$$$, где $$$\&amp;$$$ обозначает <a href="http://tiny.cc/kr13uz">побитовую операцию И</a>). Если $$$n = 1$$$, то последовательность является <span class="tex-font-style-it">растущей</span>.</p><p>Например, следующие четыре последовательности являются растущими: </p><ul> <li> $$$[2, 3, 15, 175]$$$ — в двоичном виде это $$$[10_2, 11_2, 1111_2, 10101111_2]$$$; </li><li> $$$[5]$$$ — в двоичном виде это $$$[101_2]$$$; </li><li> $$$[1, 3, 7, 15]$$$ — в двоичном виде это $$$[1_2, 11_2, 111_2, 1111_2]$$$; </li><li> $$$[0, 0, 0]$$$ — в двоичном виде это $$$[0_2, 0_2, 0_2]$$$. </li></ul><p>Следующие три последовательности не являются растущими: </p><ul> <li> $$$[3, 4, 5]$$$ — в двоичном виде это $$$[11_2, 100_2, 101_2]$$$; </li><li> $$$[5, 4, 3]$$$ — в двоичном виде это $$$[101_2, 100_2, 011_2]$$$; </li><li> $$$[1, 2, 4, 8]$$$ — в двоичном виде это $$$[0001_2, 0010_2, 0100_2, 1000_2]$$$. </li></ul><p>Рассмотрим две последовательности неотрицательных чисел $$$x_1, x_2, \dots, x_n$$$ и $$$y_1, y_2, \dots, y_n$$$. Назовём эту пару последовательностей <span class="tex-font-style-it">взаимнорастущими</span>, если последовательность $$$x_1 \oplus y_1, x_2 \oplus y_2, \dots, x_n \oplus y_n$$$ является <span class="tex-font-style-it">растущей</span>, где $$$\oplus$$$ является операцией <a href="http://tiny.cc/0s13uz">побитового исключающего ИЛИ (то есть XOR)</a>.</p><p>Задана последовательность целых чисел $$$x_1, x_2, \dots, x_n$$$. Требуется найти такую лексикографически минимальную последовательность $$$y_1, y_2, \dots, y_n$$$, что последовательности $$$x_i$$$ и $$$y_i$$$ являются взаимнорастущими.</p><p>Последовательность $$$a_1, a_2, \dots, a_n$$$ лексикографически меньше последовательности $$$b_1, b_2, \dots, b_n$$$, если существует такое $$$1 \le k \le n$$$, что для любых $$$1 \le i &lt; k$$$ выполнено $$$a_i = b_i$$$, но $$$a_k &lt; b_k$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке набора записано целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — длина последовательности $$$x_i$$$. </p><p>Вторая строка набора содержит $$$n$$$ целых чисел $$$x_1, x_2, \dots, x_n$$$ ($$$0 \le x_i &lt; 2^{30}$$$) — элементы последовательности $$$x_i$$$.</p><p>Сумма значений $$$n$$$ по всем наборам входных данных теста не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора данных выведите $$$n$$$ целых чисел $$$y_1, y_2, \dots, y_n$$$ ($$$0 \le y_i &lt; 2^{30}$$$) — лексикографически минимальную последовательность, которая является взаимнорастущей с заданной последовательностью $$$x_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 4 1 3 7 15 4 1 2 4 8 5 1 2 3 4 5 4 11 13 15 1 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 0 0 0 1 3 7 0 1 0 3 2 0 2 0 14 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="e8e4be738ed5b2efe447e3f5f70a2975"/> <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="578290d168a7daa6108dcfc3ded930345ad3b1ed"/> <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='e8e4be738ed5b2efe447e3f5f70a2975'>&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%2F1547%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='e8e4be738ed5b2efe447e3f5f70a2975'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1547">Codeforces Round 731 (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='e8e4be738ed5b2efe447e3f5f70a2975'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1547/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='e8e4be738ed5b2efe447e3f5f70a2975'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1041928"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e8e4be738ed5b2efe447e3f5f70a2975'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1041928"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92681" title="Codeforces Round #731 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13992:13993" 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/92715" title="Разбор задач Codeforces Round #731 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13994:13995" 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/1547">Задачи</a></li> <li><a href="/contest/1547/submit">Отослать</a></li> <li><a href="/contest/1547/my">Мои посылки</a></li> <li><a href="/contest/1547/status">Статус</a></li> <li><a href="/contest/1547/hacks">Взломы</a></li> <li><a href="/contest/1547/standings">Положение</a></li> <li><a href="/contest/1547/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_07044521ac7e859932d5338b4019c2ddf80cd70a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Взаимнорастущая последовательность</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Последовательность неотрицательных целых чисел $$$a_1, a_2, \dots, a_n$$$ называется <span class="tex-font-style-it">растущей</span>, если для всех $$$i$$$ от $$$1$$$ до $$$n - 1$$$ в двоичной записи $$$a_i$$$ все единичные биты стоят на местах битов, которые тоже единичные, в двоичной записи $$$a_{i + 1}$$$ (иными словами, $$$a_i \:\&amp;\: a_{i + 1} = a_i$$$, где $$$\&amp;$$$ обозначает <a href="http://tiny.cc/kr13uz">побитовую операцию И</a>). Если $$$n = 1$$$, то последовательность является <span class="tex-font-style-it">растущей</span>.</p><p>Например, следующие четыре последовательности являются растущими: </p><ul> <li> $$$[2, 3, 15, 175]$$$ — в двоичном виде это $$$[10_2, 11_2, 1111_2, 10101111_2]$$$; </li><li> $$$[5]$$$ — в двоичном виде это $$$[101_2]$$$; </li><li> $$$[1, 3, 7, 15]$$$ — в двоичном виде это $$$[1_2, 11_2, 111_2, 1111_2]$$$; </li><li> $$$[0, 0, 0]$$$ — в двоичном виде это $$$[0_2, 0_2, 0_2]$$$. </li></ul><p>Следующие три последовательности не являются растущими: </p><ul> <li> $$$[3, 4, 5]$$$ — в двоичном виде это $$$[11_2, 100_2, 101_2]$$$; </li><li> $$$[5, 4, 3]$$$ — в двоичном виде это $$$[101_2, 100_2, 011_2]$$$; </li><li> $$$[1, 2, 4, 8]$$$ — в двоичном виде это $$$[0001_2, 0010_2, 0100_2, 1000_2]$$$. </li></ul><p>Рассмотрим две последовательности неотрицательных чисел $$$x_1, x_2, \dots, x_n$$$ и $$$y_1, y_2, \dots, y_n$$$. Назовём эту пару последовательностей <span class="tex-font-style-it">взаимнорастущими</span>, если последовательность $$$x_1 \oplus y_1, x_2 \oplus y_2, \dots, x_n \oplus y_n$$$ является <span class="tex-font-style-it">растущей</span>, где $$$\oplus$$$ является операцией <a href="http://tiny.cc/0s13uz">побитового исключающего ИЛИ (то есть XOR)</a>.</p><p>Задана последовательность целых чисел $$$x_1, x_2, \dots, x_n$$$. Требуется найти такую лексикографически минимальную последовательность $$$y_1, y_2, \dots, y_n$$$, что последовательности $$$x_i$$$ и $$$y_i$$$ являются взаимнорастущими.</p><p>Последовательность $$$a_1, a_2, \dots, a_n$$$ лексикографически меньше последовательности $$$b_1, b_2, \dots, b_n$$$, если существует такое $$$1 \le k \le n$$$, что для любых $$$1 \le i &lt; k$$$ выполнено $$$a_i = b_i$$$, но $$$a_k &lt; b_k$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$). Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке набора записано целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — длина последовательности $$$x_i$$$. </p><p>Вторая строка набора содержит $$$n$$$ целых чисел $$$x_1, x_2, \dots, x_n$$$ ($$$0 \le x_i &lt; 2^{30}$$$) — элементы последовательности $$$x_i$$$.</p><p>Сумма значений $$$n$$$ по всем наборам входных данных теста не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора данных выведите $$$n$$$ целых чисел $$$y_1, y_2, \dots, y_n$$$ ($$$0 \le y_i &lt; 2^{30}$$$) — лексикографически минимальную последовательность, которая является взаимнорастущей с заданной последовательностью $$$x_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 4 1 3 7 15 4 1 2 4 8 5 1 2 3 4 5 4 11 13 15 1 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 0 0 0 1 3 7 0 1 0 3 2 0 2 0 14 0 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c8587f2c9d3a',t:'MTY5NjY2NzQzMS45NzgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*1300"]
1547E
1547
E
ru
E. Кондиционеры
<div class="problem-statement"><div class="header"><div class="title">E. Кондиционеры</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>На клетчатой полоске длины $$$n$$$ расположены $$$k$$$ кондиционеров: $$$i$$$-й кондиционер расположен в клетке $$$a_i$$$ ($$$1 \le a_i \le n$$$). Два или более кондиционера не могут находиться в одной клетке (то есть все $$$a_i$$$ различны).</p><p>Каждый кондиционер характеризуется еще одним параметром — температурой: $$$i$$$-й кондиционер включен на температуру $$$t_i$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/ae3f38f146464e062a4425bfc505873977d7a013.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-size-small">Пример полосы длины $$$n=6$$$, где $$$k=2$$$, $$$a=[2,5]$$$ и $$$t=[14,16]$$$.</span> </center><p>Для каждой клетки $$$i$$$ ($$$1 \le i \le n$$$) найдите температуру воздуха в ней, которая равна $$$$$$\min_{1 \le j \le k}(t_j + |a_j - i|),$$$$$$</p><p>где $$$|a_j - i|$$$ обозначает абсолютную величину (модуль) значения разности $$$a_j - i$$$.</p><p>Иными словами, температура в клетке $$$i$$$ равна минимуму среди температур кондиционеров, увеличенных на расстояние от кондиционера до клетки $$$i$$$.</p><p>Рассмотрим пример. Пусть $$$n=6, k=2$$$, первый кондиционер стоит в клетке $$$a_1=2$$$ включен на температуру $$$t_1=14$$$, а второй стоит в клетке $$$a_2=5$$$ и включен на температуру $$$t_2=16$$$. В таком случае температуры воздуха в клетках будут следующими:</p><ol> <li> температура в $$$1$$$-й клетке равна: $$$\min(14 + |2 - 1|, 16 + |5 - 1|)=\min(14 + 1, 16 + 4)=\min(15, 20)=15$$$; </li><li> температура во $$$2$$$-й клетке равна: $$$\min(14 + |2 - 2|, 16 + |5 - 2|)=\min(14 + 0, 16 + 3)=\min(14, 19)=14$$$; </li><li> температура в $$$3$$$-й клетке равна: $$$\min(14 + |2 - 3|, 16 + |5 - 3|)=\min(14 + 1, 16 + 2)=\min(15, 18)=15$$$; </li><li> температура в $$$4$$$-й клетке равна: $$$\min(14 + |2 - 4|, 16 + |5 - 4|)=\min(14 + 2, 16 + 1)=\min(16, 17)=16$$$; </li><li> температура в $$$5$$$-й клетке равна: $$$\min(14 + |2 - 5|, 16 + |5 - 5|)=\min(14 + 3, 16 + 0)=\min(17, 16)=16$$$; </li><li> температура в $$$6$$$-й клетке равна: $$$\min(14 + |2 - 6|, 16 + |5 - 6|)=\min(14 + 4, 16 + 1)=\min(18, 17)=17$$$. </li></ol><p>Для каждой клетки от $$$1$$$ до $$$n$$$ найдите температуру воздуха в ней.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано целое число $$$q$$$ ($$$1 \le q \le 10^4$$$) — количество наборов входных данных в тесте. Далее следуют наборы входных данных. Перед каждым набором входных данных записана пустая строка.</p><p>Каждый набор входных данный состоит из трех строк. В первой строке заданы два целых числа $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) и $$$k$$$ ($$$1 \le k \le n$$$) — длина клетчатой полоски и количество кондиционеров соответственно.</p><p>Вторая строка содержит $$$k$$$ целых чисел $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — позиции кондиционеров на клетчатой полоске.</p><p>Третья строка содержит $$$k$$$ целых чисел $$$t_1, t_2, \ldots, t_k$$$ ($$$1 \le t_i \le 10^9$$$) — температуры кондиционеров.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$3 \cdot 10^5$$$.</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 6 2 2 5 14 16 10 1 7 30 5 5 3 1 4 2 5 3 1 4 2 5 7 1 1 1000000000 6 3 6 1 3 5 5 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 14 15 16 16 17 36 35 34 33 32 31 30 31 32 33 1 2 3 4 5 1000000000 1000000001 1000000002 1000000003 1000000004 1000000005 1000000006 5 6 5 6 6 5 </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="4dfe016033f92c3a43ba3e3d351501e1"/> <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="578290d168a7daa6108dcfc3ded930345ad3b1ed"/> <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='4dfe016033f92c3a43ba3e3d351501e1'>&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%2F1547%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='4dfe016033f92c3a43ba3e3d351501e1'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1547">Codeforces Round 731 (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='4dfe016033f92c3a43ba3e3d351501e1'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1547/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='4dfe016033f92c3a43ba3e3d351501e1'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1041929"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4dfe016033f92c3a43ba3e3d351501e1'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1041929"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92681" title="Codeforces Round #731 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13992:13993" 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/92715" title="Разбор задач Codeforces Round #731 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13994:13995" 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/1547">Задачи</a></li> <li><a href="/contest/1547/submit">Отослать</a></li> <li><a href="/contest/1547/my">Мои посылки</a></li> <li><a href="/contest/1547/status">Статус</a></li> <li><a href="/contest/1547/hacks">Взломы</a></li> <li><a href="/contest/1547/standings">Положение</a></li> <li><a href="/contest/1547/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9c30cba20a4232c9614f00e5903d6961803e825e"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Кондиционеры</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>На клетчатой полоске длины $$$n$$$ расположены $$$k$$$ кондиционеров: $$$i$$$-й кондиционер расположен в клетке $$$a_i$$$ ($$$1 \le a_i \le n$$$). Два или более кондиционера не могут находиться в одной клетке (то есть все $$$a_i$$$ различны).</p><p>Каждый кондиционер характеризуется еще одним параметром — температурой: $$$i$$$-й кондиционер включен на температуру $$$t_i$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/ae3f38f146464e062a4425bfc505873977d7a013.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-size-small">Пример полосы длины $$$n=6$$$, где $$$k=2$$$, $$$a=[2,5]$$$ и $$$t=[14,16]$$$.</span> </center><p>Для каждой клетки $$$i$$$ ($$$1 \le i \le n$$$) найдите температуру воздуха в ней, которая равна $$$$$$\min_{1 \le j \le k}(t_j + |a_j - i|),$$$$$$</p><p>где $$$|a_j - i|$$$ обозначает абсолютную величину (модуль) значения разности $$$a_j - i$$$.</p><p>Иными словами, температура в клетке $$$i$$$ равна минимуму среди температур кондиционеров, увеличенных на расстояние от кондиционера до клетки $$$i$$$.</p><p>Рассмотрим пример. Пусть $$$n=6, k=2$$$, первый кондиционер стоит в клетке $$$a_1=2$$$ включен на температуру $$$t_1=14$$$, а второй стоит в клетке $$$a_2=5$$$ и включен на температуру $$$t_2=16$$$. В таком случае температуры воздуха в клетках будут следующими:</p><ol> <li> температура в $$$1$$$-й клетке равна: $$$\min(14 + |2 - 1|, 16 + |5 - 1|)=\min(14 + 1, 16 + 4)=\min(15, 20)=15$$$; </li><li> температура во $$$2$$$-й клетке равна: $$$\min(14 + |2 - 2|, 16 + |5 - 2|)=\min(14 + 0, 16 + 3)=\min(14, 19)=14$$$; </li><li> температура в $$$3$$$-й клетке равна: $$$\min(14 + |2 - 3|, 16 + |5 - 3|)=\min(14 + 1, 16 + 2)=\min(15, 18)=15$$$; </li><li> температура в $$$4$$$-й клетке равна: $$$\min(14 + |2 - 4|, 16 + |5 - 4|)=\min(14 + 2, 16 + 1)=\min(16, 17)=16$$$; </li><li> температура в $$$5$$$-й клетке равна: $$$\min(14 + |2 - 5|, 16 + |5 - 5|)=\min(14 + 3, 16 + 0)=\min(17, 16)=16$$$; </li><li> температура в $$$6$$$-й клетке равна: $$$\min(14 + |2 - 6|, 16 + |5 - 6|)=\min(14 + 4, 16 + 1)=\min(18, 17)=17$$$. </li></ol><p>Для каждой клетки от $$$1$$$ до $$$n$$$ найдите температуру воздуха в ней.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано целое число $$$q$$$ ($$$1 \le q \le 10^4$$$) — количество наборов входных данных в тесте. Далее следуют наборы входных данных. Перед каждым набором входных данных записана пустая строка.</p><p>Каждый набор входных данный состоит из трех строк. В первой строке заданы два целых числа $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) и $$$k$$$ ($$$1 \le k \le n$$$) — длина клетчатой полоски и количество кондиционеров соответственно.</p><p>Вторая строка содержит $$$k$$$ целых чисел $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — позиции кондиционеров на клетчатой полоске.</p><p>Третья строка содержит $$$k$$$ целых чисел $$$t_1, t_2, \ldots, t_k$$$ ($$$1 \le t_i \le 10^9$$$) — температуры кондиционеров.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$3 \cdot 10^5$$$.</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 6 2 2 5 14 16 10 1 7 30 5 5 3 1 4 2 5 3 1 4 2 5 7 1 1 1000000000 6 3 6 1 3 5 5 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 14 15 16 16 17 36 35 34 33 32 31 30 31 32 33 1 2 3 4 5 1000000000 1000000001 1000000002 1000000003 1000000004 1000000005 1000000006 5 6 5 6 6 5 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c86198c17b37',t:'MTY5NjY2NzQzMy4zNjYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438 \u043d\u0430 \u0433\u0440\u0430\u0444\u0430\u0445", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u043f", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\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", "*1500"]
1547F
1547
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 = [a_0, a_1, \dots, a_{n - 1}]$$$ ($$$n \ge 2$$$).</p><p>За один шаг массив $$$a$$$ заменяется на другой массив длины $$$n$$$, в котором каждый элемент это <a href="http://tiny.cc/abv9uz">наибольший общий делитель (НОД)</a> двух соседних элементов (самого элемента и его правого соседа; считайте, что правый сосед $$$(n - 1)$$$-го элемента это $$$0$$$-й элемент).</p><p>Формально говоря, по массиву $$$a = [a_0, a_1, \dots, a_{n - 1}]$$$ строится новый массив $$$b = [b_0, b_1, \dots, b_{n - 1}]$$$ такой, что $$$b_i$$$ $$$= \gcd(a_i, a_{(i + 1) \mod n})$$$, где $$$\gcd(x, y)$$$ — это наибольший общий делитель $$$x$$$ и $$$y$$$, а $$$x \mod y$$$ — это остаток от деления $$$x$$$ на $$$y$$$. За один шаг строится массив $$$b$$$, а затем массив $$$a$$$ заменяется массивом $$$b$$$ (то есть осуществляется присваивание $$$a$$$ <span class="tex-font-style-tt">:=</span> $$$b$$$).</p><p>Например, если $$$a = [16, 24, 10, 5]$$$, то $$$b = [\gcd(16, 24)$$$, $$$\gcd(24, 10)$$$, $$$\gcd(10, 5)$$$, $$$\gcd(5, 16)]$$$ $$$= [8, 2, 5, 1]$$$. Таким образом, массив $$$a = [16, 24, 10, 5]$$$ после одного шага станет равен $$$[8, 2, 5, 1]$$$.</p><p>Для заданного массива $$$a$$$ найдите минимальное количество шагов, после которых все значения $$$a_i$$$ станут равными (то есть $$$a_0 = a_1 = \dots = a_{n - 1}$$$). Если изначально массив $$$a$$$ уже состоял из одинаковых элементов, то считайте, что количество шагов равно $$$0$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее записаны $$$t$$$ наборов входных данных.</p><p>Каждый набор состоит из двух строк. В первой строке содержится целое число $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — длина массива $$$a$$$. Вторая строка содержит $$$n$$$ целых чисел $$$a_0, a_1, \dots, a_{n - 1}$$$ ($$$1 \le a_i \le 10^6$$$).</p><p>Сумма значений $$$n$$$ по всем наборам входных данных теста не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ чисел — ответы на наборы входных данных теста.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 4 16 24 10 5 4 42 42 42 42 3 4 6 4 5 1 2 3 4 5 6 9 9 27 9 9 63 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 0 2 1 1 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b8c903027fc269f3e3ea56d2ca1e658c"/> <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="578290d168a7daa6108dcfc3ded930345ad3b1ed"/> <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='b8c903027fc269f3e3ea56d2ca1e658c'>&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%2F1547%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='b8c903027fc269f3e3ea56d2ca1e658c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1547">Codeforces Round 731 (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='b8c903027fc269f3e3ea56d2ca1e658c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1547/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='b8c903027fc269f3e3ea56d2ca1e658c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1041930"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b8c903027fc269f3e3ea56d2ca1e658c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1041930"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92681" title="Codeforces Round #731 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13992:13993" 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/92715" title="Разбор задач Codeforces Round #731 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13994:13995" 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/1547">Задачи</a></li> <li><a href="/contest/1547/submit">Отослать</a></li> <li><a href="/contest/1547/my">Мои посылки</a></li> <li><a href="/contest/1547/status">Статус</a></li> <li><a href="/contest/1547/hacks">Взломы</a></li> <li><a href="/contest/1547/standings">Положение</a></li> <li><a href="/contest/1547/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_19390e97772d23d864088027e899fa68251658e5"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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 = [a_0, a_1, \dots, a_{n - 1}]$$$ ($$$n \ge 2$$$).</p><p>За один шаг массив $$$a$$$ заменяется на другой массив длины $$$n$$$, в котором каждый элемент это <a href="http://tiny.cc/abv9uz">наибольший общий делитель (НОД)</a> двух соседних элементов (самого элемента и его правого соседа; считайте, что правый сосед $$$(n - 1)$$$-го элемента это $$$0$$$-й элемент).</p><p>Формально говоря, по массиву $$$a = [a_0, a_1, \dots, a_{n - 1}]$$$ строится новый массив $$$b = [b_0, b_1, \dots, b_{n - 1}]$$$ такой, что $$$b_i$$$ $$$= \gcd(a_i, a_{(i + 1) \mod n})$$$, где $$$\gcd(x, y)$$$ — это наибольший общий делитель $$$x$$$ и $$$y$$$, а $$$x \mod y$$$ — это остаток от деления $$$x$$$ на $$$y$$$. За один шаг строится массив $$$b$$$, а затем массив $$$a$$$ заменяется массивом $$$b$$$ (то есть осуществляется присваивание $$$a$$$ <span class="tex-font-style-tt">:=</span> $$$b$$$).</p><p>Например, если $$$a = [16, 24, 10, 5]$$$, то $$$b = [\gcd(16, 24)$$$, $$$\gcd(24, 10)$$$, $$$\gcd(10, 5)$$$, $$$\gcd(5, 16)]$$$ $$$= [8, 2, 5, 1]$$$. Таким образом, массив $$$a = [16, 24, 10, 5]$$$ после одного шага станет равен $$$[8, 2, 5, 1]$$$.</p><p>Для заданного массива $$$a$$$ найдите минимальное количество шагов, после которых все значения $$$a_i$$$ станут равными (то есть $$$a_0 = a_1 = \dots = a_{n - 1}$$$). Если изначально массив $$$a$$$ уже состоял из одинаковых элементов, то считайте, что количество шагов равно $$$0$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее записаны $$$t$$$ наборов входных данных.</p><p>Каждый набор состоит из двух строк. В первой строке содержится целое число $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — длина массива $$$a$$$. Вторая строка содержит $$$n$$$ целых чисел $$$a_0, a_1, \dots, a_{n - 1}$$$ ($$$1 \le a_i \le 10^6$$$).</p><p>Сумма значений $$$n$$$ по всем наборам входных данных теста не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ чисел — ответы на наборы входных данных теста.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 4 16 24 10 5 4 42 42 42 42 3 4 6 4 5 1 2 3 4 5 6 9 9 27 9 9 63 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 0 2 1 1 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c86a3ebf9d86',t:'MTY5NjY2NzQzNC43MjUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1900"]
1547G
1547
G
ru
G. Сколько путей?
<div class="problem-statement"><div class="header"><div class="title">G. Сколько путей?</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Задан ориентированный граф $$$G$$$, в котором допустимы петли (то есть рёбра из вершины в себя). В $$$G$$$ отсутствуют кратные рёбра, то есть для каждой упорядоченной пары вершин $$$(u, v)$$$ существует не более одного ребра из $$$u$$$ в $$$v$$$. Вершины пронумерованы от $$$1$$$ до $$$n$$$.</p><p>Назовём путем из $$$u$$$ в $$$v$$$ такую последовательность рёбер, что:</p><ul> <li> вершина $$$u$$$ является началом первого ребра пути; </li><li> вершина $$$v$$$ является концом последнего ребра пути; </li><li> для любой пары соседних рёбер следующее ребро начинается с вершины, на которую заканчивается предыдущее ребро. </li></ul><p>Дополнительно будем считать, что пустая последовательность рёбер — это путь из $$$u$$$ в $$$u$$$.</p><p>Для каждой вершины $$$v$$$ выведите одно из четырёх значений:</p><ul> <li> $$$0$$$, если не существует пути из $$$1$$$ в $$$v$$$; </li><li> $$$1$$$, если существует ровно один путь из $$$1$$$ в $$$v$$$; </li><li> $$$2$$$, если существует более одного пути из $$$1$$$ в $$$v$$$ и это число является конечной величиной; </li><li> $$$-1$$$, если существует бесконечно много путей из $$$1$$$ в $$$v$$$. </li></ul><p>Рассмотрим пример, изображённый на рисунке.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/3a1f1155f410929e7304422190fcf5657b661606.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Тогда:</p><ul> <li> ответ для вершины $$$1$$$ равен $$$1$$$: существует ровно один путь из $$$1$$$ в $$$1$$$ (путь длины $$$0$$$); </li><li> ответ для вершины $$$2$$$ равен $$$0$$$: не существует пути из $$$1$$$ в $$$2$$$; </li><li> ответ для вершины $$$3$$$ равен $$$1$$$: существует ровно один путь из $$$1$$$ в $$$3$$$ (это ребро $$$(1, 3)$$$); </li><li> ответ для вершины $$$4$$$ равен $$$2$$$: существует более одного, но конечное число путей из $$$1$$$ в $$$4$$$ (два пути: $$$[(1, 3), (3, 4)]$$$ и $$$[(1, 4)]$$$); </li><li> ответ для вершины $$$5$$$ равен $$$-1$$$: существует бесконечно много путей из $$$1$$$ в $$$5$$$ (петля может быть использована в пути сколько угодно раз); </li><li> ответ для вершины $$$6$$$ равен $$$-1$$$: существует бесконечно много путей из $$$1$$$ в $$$6$$$ (петля может быть использована в пути сколько угодно раз). </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее заданы описания $$$t$$$ наборов входных данных. Перед каждым из них в тесте содержится пустая строка.</p><p>В первой строке набора входных данных записаны два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 4 \cdot 10^5, 0 \le m \le 4 \cdot 10^5$$$) — количество вершин и рёбер в графе, соответственно. Далее входные данные содержат $$$m$$$ строк с описаниями рёбер. Каждая строка состоит из двух целых чисел $$$a_i$$$, $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — начало и конец $$$i$$$-го ребра. Вершины графа пронумерованы от $$$1$$$ до $$$n$$$. Заданный граф может содержать петли (допустимо $$$a_i = b_i$$$), но не может содержать кратных рёбер (недопустимо $$$a_i = a_j$$$ и $$$b_i = b_j$$$ для $$$i \ne j$$$).</p><p>Сумма значений $$$n$$$ по всем наборам входных данных в тесте не превосходит $$$4 \cdot 10^5$$$. Аналогично, сумма значений $$$m$$$ по всем наборам входных данных в тесте не превосходит $$$4 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк. $$$i$$$-я строка должна содержать ответ на $$$i$$$-й набор входных данных — последовательность $$$n$$$ целых чисел от $$$-1$$$ до $$$2$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 6 7 1 4 1 3 3 4 4 5 2 1 5 5 5 6 1 0 3 3 1 2 2 3 3 1 5 0 4 4 1 2 2 3 1 4 4 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 0 1 2 -1 -1 1 -1 -1 -1 1 0 0 0 0 1 1 2 1 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="baf45e15855a80710d06ba51fe0d2af7"/> <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="578290d168a7daa6108dcfc3ded930345ad3b1ed"/> <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='baf45e15855a80710d06ba51fe0d2af7'>&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%2F1547%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='baf45e15855a80710d06ba51fe0d2af7'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1547">Codeforces Round 731 (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='baf45e15855a80710d06ba51fe0d2af7'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1547/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Деревья"> деревья </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *2100 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='baf45e15855a80710d06ba51fe0d2af7'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1041931"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='baf45e15855a80710d06ba51fe0d2af7'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1041931"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/92681" title="Codeforces Round #731 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13992:13993" 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/92715" title="Разбор задач Codeforces Round #731 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13994:13995" 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/1547">Задачи</a></li> <li><a href="/contest/1547/submit">Отослать</a></li> <li><a href="/contest/1547/my">Мои посылки</a></li> <li><a href="/contest/1547/status">Статус</a></li> <li><a href="/contest/1547/hacks">Взломы</a></li> <li><a href="/contest/1547/standings">Положение</a></li> <li><a href="/contest/1547/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2b1eb04967c3645f9ce9b50bfdde10c9b89b43a3"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>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>Задан ориентированный граф $$$G$$$, в котором допустимы петли (то есть рёбра из вершины в себя). В $$$G$$$ отсутствуют кратные рёбра, то есть для каждой упорядоченной пары вершин $$$(u, v)$$$ существует не более одного ребра из $$$u$$$ в $$$v$$$. Вершины пронумерованы от $$$1$$$ до $$$n$$$.</p><p>Назовём путем из $$$u$$$ в $$$v$$$ такую последовательность рёбер, что:</p><ul> <li> вершина $$$u$$$ является началом первого ребра пути; </li><li> вершина $$$v$$$ является концом последнего ребра пути; </li><li> для любой пары соседних рёбер следующее ребро начинается с вершины, на которую заканчивается предыдущее ребро. </li></ul><p>Дополнительно будем считать, что пустая последовательность рёбер — это путь из $$$u$$$ в $$$u$$$.</p><p>Для каждой вершины $$$v$$$ выведите одно из четырёх значений:</p><ul> <li> $$$0$$$, если не существует пути из $$$1$$$ в $$$v$$$; </li><li> $$$1$$$, если существует ровно один путь из $$$1$$$ в $$$v$$$; </li><li> $$$2$$$, если существует более одного пути из $$$1$$$ в $$$v$$$ и это число является конечной величиной; </li><li> $$$-1$$$, если существует бесконечно много путей из $$$1$$$ в $$$v$$$. </li></ul><p>Рассмотрим пример, изображённый на рисунке.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/3a1f1155f410929e7304422190fcf5657b661606.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Тогда:</p><ul> <li> ответ для вершины $$$1$$$ равен $$$1$$$: существует ровно один путь из $$$1$$$ в $$$1$$$ (путь длины $$$0$$$); </li><li> ответ для вершины $$$2$$$ равен $$$0$$$: не существует пути из $$$1$$$ в $$$2$$$; </li><li> ответ для вершины $$$3$$$ равен $$$1$$$: существует ровно один путь из $$$1$$$ в $$$3$$$ (это ребро $$$(1, 3)$$$); </li><li> ответ для вершины $$$4$$$ равен $$$2$$$: существует более одного, но конечное число путей из $$$1$$$ в $$$4$$$ (два пути: $$$[(1, 3), (3, 4)]$$$ и $$$[(1, 4)]$$$); </li><li> ответ для вершины $$$5$$$ равен $$$-1$$$: существует бесконечно много путей из $$$1$$$ в $$$5$$$ (петля может быть использована в пути сколько угодно раз); </li><li> ответ для вершины $$$6$$$ равен $$$-1$$$: существует бесконечно много путей из $$$1$$$ в $$$6$$$ (петля может быть использована в пути сколько угодно раз). </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее заданы описания $$$t$$$ наборов входных данных. Перед каждым из них в тесте содержится пустая строка.</p><p>В первой строке набора входных данных записаны два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 4 \cdot 10^5, 0 \le m \le 4 \cdot 10^5$$$) — количество вершин и рёбер в графе, соответственно. Далее входные данные содержат $$$m$$$ строк с описаниями рёбер. Каждая строка состоит из двух целых чисел $$$a_i$$$, $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — начало и конец $$$i$$$-го ребра. Вершины графа пронумерованы от $$$1$$$ до $$$n$$$. Заданный граф может содержать петли (допустимо $$$a_i = b_i$$$), но не может содержать кратных рёбер (недопустимо $$$a_i = a_j$$$ и $$$b_i = b_j$$$ для $$$i \ne j$$$).</p><p>Сумма значений $$$n$$$ по всем наборам входных данных в тесте не превосходит $$$4 \cdot 10^5$$$. Аналогично, сумма значений $$$m$$$ по всем наборам входных данных в тесте не превосходит $$$4 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк. $$$i$$$-я строка должна содержать ответ на $$$i$$$-й набор входных данных — последовательность $$$n$$$ целых чисел от $$$-1$$$ до $$$2$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 6 7 1 4 1 3 3 4 4 5 2 1 5 5 5 6 1 0 3 3 1 2 2 3 3 1 5 0 4 4 1 2 2 3 1 4 4 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 0 1 2 -1 -1 1 -1 -1 -1 1 0 0 0 0 1 1 2 1 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=G]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c872a8fd9d90',t:'MTY5NjY2NzQzNi4xNjkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*2100"]
1548A
1548
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><div class="epigraph"><div class="epigraph-text">Когда играешь в игру престолов, ты побеждаешь или умираешь. Третьего не дано.</div><div class="epigraph-source">Серсея Ланнистер, <span class="tex-font-style-it">Игра престолов</span>, Джордж Р. Р. Мартин</div></div><p>Есть $$$n$$$ дворян, пронумерованных от $$$1$$$ до $$$n$$$. Дворянин $$$i$$$ обладает могуществом $$$i$$$. Дворяне «дружат» между собой — всего есть $$$m$$$ пар дружных дворян. Дружба между дворянами $$$a$$$ и $$$b$$$ всегда взаимная. </p><p>Дворянин считается <span class="tex-font-style-it">уязвимым</span>, если выполнены оба следующих условия. </p><ul> <li> у этого дворянина есть хотя бы один друг, и </li><li> <span class="tex-font-style-bf">все</span> друзья этого дворянина обладают могуществом, превосходящим могущество этого дворянина. </li></ul><p>Вам нужно будет обрабатывать следующие три типа запросов. </p><ol> <li> Добавить дружбу между $$$u$$$ и $$$v$$$. </li><li> Удалить дружбу между $$$u$$$ и $$$v$$$. </li><li> Посчитать ответ на следующий процесс. </li></ol><p>Процесс: все уязвимые дворяне одновременно умирают, и все их дружбы заканчиваются. После этого, возможно, некоторые другие дворяне становятся уязвимыми. Процесс повторяется до тех пор, пока есть уязвимые дворяне. Можно доказать, что процесс завершится за конечное число шагов. После завершения процесса вам необходимо посчитать количество оставшихся дворян. </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>Следующие $$$m$$$ строк содержат по два целых числа $$$u$$$ и $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$), описывающие дружбу между дворянами. Никакая пара друзей не повторяется дважды.</p><p>Следующая строка содержит целое число $$$q$$$ ($$$1 \le q \le 2\cdot {10}^{5}$$$) — количество запросов. </p><p>Следующие $$$q$$$ строк содержат сами запросы по одному в строке. Каждый запрос имеет один из следующих видов: </p><ul> <li> $$$1$$$ $$$u$$$ $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$) — добавить дружбу между $$$u$$$ и $$$v$$$. Гарантируется, что $$$u$$$ и $$$v$$$ не друзья в этот момент. </li><li> $$$2$$$ $$$u$$$ $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$) — удалить дружбу между $$$u$$$ и $$$v$$$. Гарантируется, что $$$u$$$ и $$$v$$$ дружат в этот момент. </li><li> $$$3$$$ — вывести ответ на процесс, описанный в условии. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос $$$3$$$-го типа выведите целое число, по одному на строку. Гарантируется, что будет хотя бы один запрос типа $$$3$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 1 1 3 3 4 4 3 1 2 3 2 3 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 3 3 4 4 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ситуация в первом запросе типа 3 изображена на рисунке ниже.</p><p>В первом раунде процесса дворянин $$$1$$$ слабее, чем все его друзья ($$$2$$$ и $$$3$$$), и поэтому он умирает. Никакой другой дворянин в раунде 1 не является уязвимым. В раунде 2 дворянин $$$3$$$ слабее своего единственного друга, дворянина $$$4$$$, и поэтому он умирает. На этом этапе процесс завершается, ответ равен $$$2$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/cbaf66d5c268440ab9f4754a89be088c6d87b738.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Во втором запросе типа 3 единственным выжившим является дворянин $$$4$$$.</p><p>    </p><p>Второй пример состоит только из одного запроса типа $$$3$$$. В первом раунде умирают два дворянина, во втором раунде умирает один дворянин. Итоговый ответ равен $$$1$$$, поскольку только один дворянин выжил. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8631f2c909305073cf264f22183338c334c8d19e.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="6dd6a629c164589169c6bba106a70095"/> <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="ee09f07644402b5410765db8004aff1e6ad5a858"/> <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='6dd6a629c164589169c6bba106a70095'>&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%2F1548%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='6dd6a629c164589169c6bba106a70095'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1548">Codeforces Round 736 (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='6dd6a629c164589169c6bba106a70095'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1548/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='6dd6a629c164589169c6bba106a70095'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1062382"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6dd6a629c164589169c6bba106a70095'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1062382"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/93361" title="Codeforces Round #736" target="_blank">Codeforces Round #736 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14106" resourceName="Codeforces Round #736" resourceManual="true" src="//codeforces.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/93586" title="Codeforces Round 736 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14141" resourceName="Codeforces Round 736 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/1548">Задачи</a></li> <li><a href="/contest/1548/submit">Отослать</a></li> <li><a href="/contest/1548/my">Мои посылки</a></li> <li><a href="/contest/1548/status">Статус</a></li> <li><a href="/contest/1548/hacks">Взломы</a></li> <li><a href="/contest/1548/room/1">Комната</a></li> <li><a href="/contest/1548/standings">Положение</a></li> <li><a href="/contest/1548/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_aef5c3a7dbcebfc74df196b6e5f05a21449e1b30"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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><div class="epigraph"><div class="epigraph-text">Когда играешь в игру престолов, ты побеждаешь или умираешь. Третьего не дано.</div><div class="epigraph-source">Серсея Ланнистер, <span class="tex-font-style-it">Игра престолов</span>, Джордж Р. Р. Мартин</div></div><p>Есть $$$n$$$ дворян, пронумерованных от $$$1$$$ до $$$n$$$. Дворянин $$$i$$$ обладает могуществом $$$i$$$. Дворяне «дружат» между собой — всего есть $$$m$$$ пар дружных дворян. Дружба между дворянами $$$a$$$ и $$$b$$$ всегда взаимная. </p><p>Дворянин считается <span class="tex-font-style-it">уязвимым</span>, если выполнены оба следующих условия. </p><ul> <li> у этого дворянина есть хотя бы один друг, и </li><li> <span class="tex-font-style-bf">все</span> друзья этого дворянина обладают могуществом, превосходящим могущество этого дворянина. </li></ul><p>Вам нужно будет обрабатывать следующие три типа запросов. </p><ol> <li> Добавить дружбу между $$$u$$$ и $$$v$$$. </li><li> Удалить дружбу между $$$u$$$ и $$$v$$$. </li><li> Посчитать ответ на следующий процесс. </li></ol><p>Процесс: все уязвимые дворяне одновременно умирают, и все их дружбы заканчиваются. После этого, возможно, некоторые другие дворяне становятся уязвимыми. Процесс повторяется до тех пор, пока есть уязвимые дворяне. Можно доказать, что процесс завершится за конечное число шагов. После завершения процесса вам необходимо посчитать количество оставшихся дворян. </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>Следующие $$$m$$$ строк содержат по два целых числа $$$u$$$ и $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$), описывающие дружбу между дворянами. Никакая пара друзей не повторяется дважды.</p><p>Следующая строка содержит целое число $$$q$$$ ($$$1 \le q \le 2\cdot {10}^{5}$$$) — количество запросов. </p><p>Следующие $$$q$$$ строк содержат сами запросы по одному в строке. Каждый запрос имеет один из следующих видов: </p><ul> <li> $$$1$$$ $$$u$$$ $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$) — добавить дружбу между $$$u$$$ и $$$v$$$. Гарантируется, что $$$u$$$ и $$$v$$$ не друзья в этот момент. </li><li> $$$2$$$ $$$u$$$ $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$) — удалить дружбу между $$$u$$$ и $$$v$$$. Гарантируется, что $$$u$$$ и $$$v$$$ дружат в этот момент. </li><li> $$$3$$$ — вывести ответ на процесс, описанный в условии. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос $$$3$$$-го типа выведите целое число, по одному на строку. Гарантируется, что будет хотя бы один запрос типа $$$3$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 1 1 3 3 4 4 3 1 2 3 2 3 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 3 3 4 4 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ситуация в первом запросе типа 3 изображена на рисунке ниже.</p><p>В первом раунде процесса дворянин $$$1$$$ слабее, чем все его друзья ($$$2$$$ и $$$3$$$), и поэтому он умирает. Никакой другой дворянин в раунде 1 не является уязвимым. В раунде 2 дворянин $$$3$$$ слабее своего единственного друга, дворянина $$$4$$$, и поэтому он умирает. На этом этапе процесс завершается, ответ равен $$$2$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/cbaf66d5c268440ab9f4754a89be088c6d87b738.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во втором запросе типа 3 единственным выжившим является дворянин $$$4$$$.</p><p>    </p><p>Второй пример состоит только из одного запроса типа $$$3$$$. В первом раунде умирают два дворянина, во втором раунде умирает один дворянин. Итоговый ответ равен $$$1$$$, поскольку только один дворянин выжил. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8631f2c909305073cf264f22183338c334c8d19e.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c87bb9769daa',t:'MTY5NjY2NzQzNy42NDQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u0435\u0440\u0435\u0431\u043e\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\u0435\u0440\u0435\u0431\u043e\u0440", "*1400"]
1548B
1548
B
ru
B. У чисел есть друзья
<div class="problem-statement"><div class="header"><div class="title">B. У чисел есть друзья</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Британский математик Джон Литлвуд однажды высказался об индийском математике Сринивасе Рамануджане: «каждое натуральное число было его личным другом».</p><p>Оказывается, натуральные числа могут также дружить друг с другом! Вам дан массив $$$a$$$ из различных натуральных чисел.</p><p>Будем называть <span class="tex-font-style-bf">подмассив</span> $$$a_i, a_{i+1}, \ldots, a_j$$$ <span class="tex-font-style-it">группой друзей</span> тогда и только тогда, когда существует целое число $$$m \ge 2$$$ такое, что $$$a_i \bmod m = a_{i+1} \bmod m = \ldots = a_j \bmod m$$$, где $$$x \bmod y$$$ обозначает остаток от деления $$$x$$$ на $$$y$$$.</p><p>Ваш друг Грегор хочет знать размер наибольшей группы друзей в $$$a$$$. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит количество наборов входных данных $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$).</p><p>Первая строка каждого набора содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) – размера массива $$$a$$$.</p><p>Вторая строка набора содержит $$$n$$$ натуральных чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le {10}^{18}$$$) – содержимое массива $$$a$$$. Гарантируется, что все числа в $$$a$$$ <span class="tex-font-style-bf">различны</span>.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных меньше $$$2\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Ваш вывод должен состоять из $$$t$$$ строк. Каждая строка должна содержать одно целое число — размер наибольшей группы друзей из $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 1 5 2 4 6 4 8 2 5 10 2 1000 2000 8 465 55 3 54 234 12 45 78 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 3 2 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе массив равен $$$[1,5,2,4,6]$$$. Наибольшая группа друзей здесь $$$[2,4,6]$$$, потому что все эти числа сравнимы с $$$0$$$ по модулю $$$2$$$, таким образом $$$m=2$$$.</p><p>В первом наборе массив равен $$$[8,2,5,10]$$$. Наибольшая группа друзей здесь $$$[8,2,5]$$$, потому что все эти числа сравнимы с $$$2$$$ по модулю $$$3$$$, таким образом $$$m=3$$$.</p><p>В третьем наборе наибольшая группа друзей равна $$$[1000,2000]$$$. Существует несколько возможных подходящих значений $$$m$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="bc054a38d87ce95cbfc498c85ec5d7d0"/> <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="ee09f07644402b5410765db8004aff1e6ad5a858"/> <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='bc054a38d87ce95cbfc498c85ec5d7d0'>&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%2F1548%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='bc054a38d87ce95cbfc498c85ec5d7d0'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1548">Codeforces Round 736 (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='bc054a38d87ce95cbfc498c85ec5d7d0'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1548/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='bc054a38d87ce95cbfc498c85ec5d7d0'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1062383"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='bc054a38d87ce95cbfc498c85ec5d7d0'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1062383"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/93361" title="Codeforces Round #736" target="_blank">Codeforces Round #736 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14106" resourceName="Codeforces Round #736" resourceManual="true" src="//codeforces.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/93586" title="Codeforces Round 736 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14141" resourceName="Codeforces Round 736 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/1548">Задачи</a></li> <li><a href="/contest/1548/submit">Отослать</a></li> <li><a href="/contest/1548/my">Мои посылки</a></li> <li><a href="/contest/1548/status">Статус</a></li> <li><a href="/contest/1548/hacks">Взломы</a></li> <li><a href="/contest/1548/room/1">Комната</a></li> <li><a href="/contest/1548/standings">Положение</a></li> <li><a href="/contest/1548/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b6d7ecf8270c961d3a8794c8ae0cfd7f0dea7da2"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div> <span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">&times;</span> </div> <div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. У чисел есть друзья</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Британский математик Джон Литлвуд однажды высказался об индийском математике Сринивасе Рамануджане: «каждое натуральное число было его личным другом».</p><p>Оказывается, натуральные числа могут также дружить друг с другом! Вам дан массив $$$a$$$ из различных натуральных чисел.</p><p>Будем называть <span class="tex-font-style-bf">подмассив</span> $$$a_i, a_{i+1}, \ldots, a_j$$$ <span class="tex-font-style-it">группой друзей</span> тогда и только тогда, когда существует целое число $$$m \ge 2$$$ такое, что $$$a_i \bmod m = a_{i+1} \bmod m = \ldots = a_j \bmod m$$$, где $$$x \bmod y$$$ обозначает остаток от деления $$$x$$$ на $$$y$$$.</p><p>Ваш друг Грегор хочет знать размер наибольшей группы друзей в $$$a$$$. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит количество наборов входных данных $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$).</p><p>Первая строка каждого набора содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) – размера массива $$$a$$$.</p><p>Вторая строка набора содержит $$$n$$$ натуральных чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le {10}^{18}$$$) – содержимое массива $$$a$$$. Гарантируется, что все числа в $$$a$$$ <span class="tex-font-style-bf">различны</span>.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных меньше $$$2\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Ваш вывод должен состоять из $$$t$$$ строк. Каждая строка должна содержать одно целое число — размер наибольшей группы друзей из $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 1 5 2 4 6 4 8 2 5 10 2 1000 2000 8 465 55 3 54 234 12 45 78 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 3 2 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе массив равен $$$[1,5,2,4,6]$$$. Наибольшая группа друзей здесь $$$[2,4,6]$$$, потому что все эти числа сравнимы с $$$0$$$ по модулю $$$2$$$, таким образом $$$m=2$$$.</p><p>В первом наборе массив равен $$$[8,2,5,10]$$$. Наибольшая группа друзей здесь $$$[8,2,5]$$$, потому что все эти числа сравнимы с $$$2$$$ по модулю $$$3$$$, таким образом $$$m=3$$$.</p><p>В третьем наборе наибольшая группа друзей равна $$$[1000,2000]$$$. Существует несколько возможных подходящих значений $$$m$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c884e9af3aa1',t:'MTY5NjY2NzQzOC45NTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1800"]
1548C
1548
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>Делегации трех поросят со всего мира едут на конференцию! Каждую минуту новая тройка поросят прибывает в конференц-зал. После $$$n$$$-й минуты конференция завершается. </p><p>Большой злой волк узнал об этой конференции и запланировал атаку. В определенную минуту конференции он ворвется в зал, съест ровно $$$x$$$ поросят и убежит. </p><p>Волк попросил Грегора помочь ему найти количество возможных планов для атаки, в которых он съест ровно $$$x$$$ поросят, для различных значений $$$x$$$ ($$$1 \le x \le 3n$$$). Два плана для атаки считаются различными, если атака происходит в различное время, или съедаются различные подмножества поросят. </p><p>Обратите внимание, что все запросы независимы, то есть в действительности волк не ест поросят, а только строит планы!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$q$$$ ($$$1 \le n \le 10^6$$$, $$$1 \le q \le 2\cdot 10^5$$$) — количество минут, которые продлится конференция, и количество запросов, которые сделает волк. </p><p>Следующие $$$q$$$ строк содержат по одному целому числу $$$x_i$$$ ($$$1 \le x_i \le 3n$$$) – количество поросят, которых съест волк в $$$i$$$-м запросе.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Вы должны вывести $$$q$$$ строк. В $$$i$$$-й строке должно содержаться количество планов для атаки, если волк хочет съесть $$$x_i$$$ поросят. Выведите каждый ответ по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 3 1 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 6 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 4 2 4 6 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 225 2001 6014 6939 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В приведенном примере $$$n=2$$$. Таким образом, на минуте $$$1$$$ в конференц-зале присутствуют $$$3$$$ поросенка, на минуте $$$2$$$ — $$$6$$$ поросят. Даны три запроса: $$$x=1$$$, $$$x=5$$$ и $$$x=6$$$.</p><p>Если волк хочет съесть $$$1$$$ поросенка, он может сделать это, используя $$$3+6=9$$$ возможных планов для атаки в зависимости от того, на какой минуте ($$$1$$$ или $$$2$$$) он прибудет.</p><p>Если волк хочет съесть $$$5$$$ поросят, он не может прибыть на минуте $$$1$$$, поскольку в это время в зале недостаточно поросят. Поэтому волк должен прибыть на минуте $$$2$$$ — тогда существует $$$6$$$ возможных планов для атаки.</p><p>Если волк хочет съесть $$$6$$$ поросят, то его единственным планом является прибыть к концу конференции и поглотить всех.</p><p>Не забудьте выводить ответы по модулю $$$10^9+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="1e4565fdcd926555489f073b0f95528c"/> <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="ee09f07644402b5410765db8004aff1e6ad5a858"/> <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='1e4565fdcd926555489f073b0f95528c'>&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%2F1548%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='1e4565fdcd926555489f073b0f95528c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1548">Codeforces Round 736 (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='1e4565fdcd926555489f073b0f95528c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1548/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='1e4565fdcd926555489f073b0f95528c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1062384"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1e4565fdcd926555489f073b0f95528c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1062384"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/93361" title="Codeforces Round #736" target="_blank">Codeforces Round #736 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14106" resourceName="Codeforces Round #736" resourceManual="true" src="//codeforces.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/93586" title="Codeforces Round 736 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14141" resourceName="Codeforces Round 736 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/1548">Задачи</a></li> <li><a href="/contest/1548/submit">Отослать</a></li> <li><a href="/contest/1548/my">Мои посылки</a></li> <li><a href="/contest/1548/status">Статус</a></li> <li><a href="/contest/1548/hacks">Взломы</a></li> <li><a href="/contest/1548/room/1">Комната</a></li> <li><a href="/contest/1548/standings">Положение</a></li> <li><a href="/contest/1548/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_43f4842085629e95ce8c6bbeca8178e557b8b4e4"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Делегации трех поросят со всего мира едут на конференцию! Каждую минуту новая тройка поросят прибывает в конференц-зал. После $$$n$$$-й минуты конференция завершается. </p><p>Большой злой волк узнал об этой конференции и запланировал атаку. В определенную минуту конференции он ворвется в зал, съест ровно $$$x$$$ поросят и убежит. </p><p>Волк попросил Грегора помочь ему найти количество возможных планов для атаки, в которых он съест ровно $$$x$$$ поросят, для различных значений $$$x$$$ ($$$1 \le x \le 3n$$$). Два плана для атаки считаются различными, если атака происходит в различное время, или съедаются различные подмножества поросят. </p><p>Обратите внимание, что все запросы независимы, то есть в действительности волк не ест поросят, а только строит планы!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$q$$$ ($$$1 \le n \le 10^6$$$, $$$1 \le q \le 2\cdot 10^5$$$) — количество минут, которые продлится конференция, и количество запросов, которые сделает волк. </p><p>Следующие $$$q$$$ строк содержат по одному целому числу $$$x_i$$$ ($$$1 \le x_i \le 3n$$$) – количество поросят, которых съест волк в $$$i$$$-м запросе.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Вы должны вывести $$$q$$$ строк. В $$$i$$$-й строке должно содержаться количество планов для атаки, если волк хочет съесть $$$x_i$$$ поросят. Выведите каждый ответ по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 3 1 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 6 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 4 2 4 6 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 225 2001 6014 6939 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В приведенном примере $$$n=2$$$. Таким образом, на минуте $$$1$$$ в конференц-зале присутствуют $$$3$$$ поросенка, на минуте $$$2$$$ — $$$6$$$ поросят. Даны три запроса: $$$x=1$$$, $$$x=5$$$ и $$$x=6$$$.</p><p>Если волк хочет съесть $$$1$$$ поросенка, он может сделать это, используя $$$3+6=9$$$ возможных планов для атаки в зависимости от того, на какой минуте ($$$1$$$ или $$$2$$$) он прибудет.</p><p>Если волк хочет съесть $$$5$$$ поросят, он не может прибыть на минуте $$$1$$$, поскольку в это время в зале недостаточно поросят. Поэтому волк должен прибыть на минуте $$$2$$$ — тогда существует $$$6$$$ возможных планов для атаки.</p><p>Если волк хочет съесть $$$6$$$ поросят, то его единственным планом является прибыть к концу конференции и поглотить всех.</p><p>Не забудьте выводить ответы по модулю $$$10^9+7$$$!</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c88d4b789d9f',t:'MTY5NjY2NzQ0MC4yOTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u043f\u0444", "\u0434\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*2500"]
1548D1
1548
D1
ru
D1. Грегор и нечетные коровы (простая версия)
<div class="problem-statement"><div class="header"><div class="title">D1. Грегор и нечетные коровы (простая версия)</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><span class="tex-font-style-it">Это простая версия задачи. Единственное отличие от сложной версии заключается в том, что в данной версии все координаты — <span class="tex-font-style-bf">четные</span> числа.</span></p><p>Даны $$$n$$$ столбов, расположенных в различных точках на плоскости. Гарантируется, что никакие три столба не лежат на одной прямой. </p><p>На плоскости также есть бесконечное количество коров, по одной в каждой точке с целочисленными координатами. </p><p>Грегор — член общества иллюминатов и хочет построить треугольный загон, соединив $$$3$$$ различных существующих столба забором. Корова, находящаяся <span class="tex-font-style-bf">строго</span> внутри загона, считается <span class="tex-font-style-it">огражденной</span>. Если ограждено <span class="tex-font-style-bf">нечётное</span> число коров, и при этом площадь загона равна <span class="tex-font-style-bf">целому</span> числу, то загон считается <span class="tex-font-style-it">интересным</span>.</p><p>Найдите количество интересных загонов. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$3 \le n \le 6000$$$) — количество столбов, которые Грегор может выбрать в качестве вершин загона.</p><p>Следующие $$$n$$$ строк содержат по два целых числа $$$x$$$ и $$$y$$$ ($$$0 \le x,y \le 10^7$$$, $$$x$$$ и $$$y$$$ — <span class="tex-font-style-bf">четные</span> числа), где $$$(x,y)$$$ — координата очередного столба. Все столбы расположены в различных точках. Никакие три столба не лежат на одной прямой.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Напечатайте одно целое число — количество интересных загонов. Два загона считаются различными, если они образованы различными множествами трех столбов. </p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 0 0 2 0 0 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 0 0 2 16 30 14 4 6 2 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере существует только $$$1$$$ загон. Этот загон является интересным, поскольку его площадь равна $$$4$$$ и есть $$$1$$$ пойманная корова, помеченная красным. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/9e3ef13118f82e89c5ddcd89348c8703ec6ea5bf.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Во втором примере есть $$$3$$$ интересных забора. </p><ul> <li> $$$(0,0)$$$ — $$$(30,14)$$$ — $$$(2,10)$$$ </li><li> $$$(2,16)$$$ — $$$(30,14)$$$ — $$$(2,10)$$$ </li><li> $$$(30,14)$$$ — $$$(4,6)$$$ — $$$(2,10)$$$ </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="85a2c2f7a0ed2726cbcd55e6cd4c4058"/> <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="ee09f07644402b5410765db8004aff1e6ad5a858"/> <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='85a2c2f7a0ed2726cbcd55e6cd4c4058'>&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%2F1548%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='85a2c2f7a0ed2726cbcd55e6cd4c4058'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1548">Codeforces Round 736 (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='85a2c2f7a0ed2726cbcd55e6cd4c4058'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1548/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='85a2c2f7a0ed2726cbcd55e6cd4c4058'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1062385"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='85a2c2f7a0ed2726cbcd55e6cd4c4058'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1062385"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/93361" title="Codeforces Round #736" target="_blank">Codeforces Round #736 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14106" resourceName="Codeforces Round #736" resourceManual="true" src="//codeforces.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/93586" title="Codeforces Round 736 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14141" resourceName="Codeforces Round 736 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/1548">Задачи</a></li> <li><a href="/contest/1548/submit">Отослать</a></li> <li><a href="/contest/1548/my">Мои посылки</a></li> <li><a href="/contest/1548/status">Статус</a></li> <li><a href="/contest/1548/hacks">Взломы</a></li> <li><a href="/contest/1548/room/1">Комната</a></li> <li><a href="/contest/1548/standings">Положение</a></li> <li><a href="/contest/1548/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_4cbe2bb4226a2a735ab01a6e7136d1d50ebfd30f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>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><span class="tex-font-style-it">Это простая версия задачи. Единственное отличие от сложной версии заключается в том, что в данной версии все координаты — <span class="tex-font-style-bf">четные</span> числа.</span></p><p>Даны $$$n$$$ столбов, расположенных в различных точках на плоскости. Гарантируется, что никакие три столба не лежат на одной прямой. </p><p>На плоскости также есть бесконечное количество коров, по одной в каждой точке с целочисленными координатами. </p><p>Грегор — член общества иллюминатов и хочет построить треугольный загон, соединив $$$3$$$ различных существующих столба забором. Корова, находящаяся <span class="tex-font-style-bf">строго</span> внутри загона, считается <span class="tex-font-style-it">огражденной</span>. Если ограждено <span class="tex-font-style-bf">нечётное</span> число коров, и при этом площадь загона равна <span class="tex-font-style-bf">целому</span> числу, то загон считается <span class="tex-font-style-it">интересным</span>.</p><p>Найдите количество интересных загонов. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$3 \le n \le 6000$$$) — количество столбов, которые Грегор может выбрать в качестве вершин загона.</p><p>Следующие $$$n$$$ строк содержат по два целых числа $$$x$$$ и $$$y$$$ ($$$0 \le x,y \le 10^7$$$, $$$x$$$ и $$$y$$$ — <span class="tex-font-style-bf">четные</span> числа), где $$$(x,y)$$$ — координата очередного столба. Все столбы расположены в различных точках. Никакие три столба не лежат на одной прямой.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Напечатайте одно целое число — количество интересных загонов. Два загона считаются различными, если они образованы различными множествами трех столбов. </p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 0 0 2 0 0 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 0 0 2 16 30 14 4 6 2 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере существует только $$$1$$$ загон. Этот загон является интересным, поскольку его площадь равна $$$4$$$ и есть $$$1$$$ пойманная корова, помеченная красным. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/9e3ef13118f82e89c5ddcd89348c8703ec6ea5bf.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во втором примере есть $$$3$$$ интересных забора. </p><ul> <li> $$$(0,0)$$$ — $$$(30,14)$$$ — $$$(2,10)$$$ </li><li> $$$(2,16)$$$ — $$$(30,14)$$$ — $$$(2,10)$$$ </li><li> $$$(30,14)$$$ — $$$(4,6)$$$ — $$$(2,10)$$$ </li></ul></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 11:30: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:'8124c8958f881693',t:'MTY5NjY2NzQ0MS42NjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0413\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\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", "\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*2300"]
1548D2
1548
D2
ru
D2. Грегор и нечетные коровы (сложная версия)
<div class="problem-statement"><div class="header"><div class="title">D2. Грегор и нечетные коровы (сложная версия)</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><span class="tex-font-style-it">Это сложная версия задачи. Единственное отличие от простой версии заключается в том, что в данной версии координаты могут быть как <span class="tex-font-style-bf">чётными</span>, так и <span class="tex-font-style-bf">нечётными</span>.</span></p><p>Даны $$$n$$$ столбов, расположенных в различных точках на плоскости. Гарантируется, что никакие три столба не лежат на одной прямой. </p><p>На плоскости также есть бесконечное количество коров, по одной в каждой точке с целочисленными координатами. </p><p>Грегор — член общества иллюминатов и хочет построить треугольный загон, соединив $$$3$$$ различных существующих столба забором. Корова, находящаяся <span class="tex-font-style-bf">строго</span> внутри загона, считается <span class="tex-font-style-it">огражденной</span>. Если ограждено <span class="tex-font-style-bf">нечётное</span> число коров, и при этом площадь загона равна <span class="tex-font-style-bf">целому</span> числу, то загон считается <span class="tex-font-style-it">интересным</span>.</p><p>Найдите количество интересных загонов. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$3 \le n \le 6000$$$) — количество столбов, которые Грегор может выбрать в качестве вершин загона.</p><p>Следующие $$$n$$$ строк содержат по два целых числа $$$x$$$ и $$$y$$$ ($$$0 \le x,y \le 10^7$$$, где $$$(x,y)$$$ — координата очередного столба. Все столбы расположены в различных точках. Никакие три столба не лежат на одной прямой.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Напечатайте одно целое число — количество интересных загонов. Два загона считаются различными, если они образованы различными множествами трех столбов. </p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 0 0 2 0 0 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 8 0 6 5 2 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 170 59 129 54 5 98 129 37 58 193 154 58 24 3 13 138 136 144 174 150 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 29 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере существует только $$$1$$$ загон. Этот загон является интересным, поскольку его площадь равна $$$4$$$ и есть $$$1$$$ пойманная корова, помеченная красным. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/9e3ef13118f82e89c5ddcd89348c8703ec6ea5bf.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Во втором примере существует $$$4$$$ возможных загона. Однако, только один из них является интересным. Этот загон имеет площадь, равную $$$8$$$, и $$$5$$$ пойманных коров.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/54519830da1f6e61df2d41e2713f59bd51424189.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="92acc426553fc136edd53dc8c70970d6"/> <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="ee09f07644402b5410765db8004aff1e6ad5a858"/> <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='92acc426553fc136edd53dc8c70970d6'>&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%2F1548%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='92acc426553fc136edd53dc8c70970d6'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1548">Codeforces Round 736 (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='92acc426553fc136edd53dc8c70970d6'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1548/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='92acc426553fc136edd53dc8c70970d6'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1062386"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='92acc426553fc136edd53dc8c70970d6'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1062386"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/93361" title="Codeforces Round #736" target="_blank">Codeforces Round #736 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14106" resourceName="Codeforces Round #736" resourceManual="true" src="//codeforces.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/93586" title="Codeforces Round 736 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14141" resourceName="Codeforces Round 736 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/1548">Задачи</a></li> <li><a href="/contest/1548/submit">Отослать</a></li> <li><a href="/contest/1548/my">Мои посылки</a></li> <li><a href="/contest/1548/status">Статус</a></li> <li><a href="/contest/1548/hacks">Взломы</a></li> <li><a href="/contest/1548/room/1">Комната</a></li> <li><a href="/contest/1548/standings">Положение</a></li> <li><a href="/contest/1548/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b653e4fd38e48f6e7f3f1eee7ccf5e5a88d055c2"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>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><span class="tex-font-style-it">Это сложная версия задачи. Единственное отличие от простой версии заключается в том, что в данной версии координаты могут быть как <span class="tex-font-style-bf">чётными</span>, так и <span class="tex-font-style-bf">нечётными</span>.</span></p><p>Даны $$$n$$$ столбов, расположенных в различных точках на плоскости. Гарантируется, что никакие три столба не лежат на одной прямой. </p><p>На плоскости также есть бесконечное количество коров, по одной в каждой точке с целочисленными координатами. </p><p>Грегор — член общества иллюминатов и хочет построить треугольный загон, соединив $$$3$$$ различных существующих столба забором. Корова, находящаяся <span class="tex-font-style-bf">строго</span> внутри загона, считается <span class="tex-font-style-it">огражденной</span>. Если ограждено <span class="tex-font-style-bf">нечётное</span> число коров, и при этом площадь загона равна <span class="tex-font-style-bf">целому</span> числу, то загон считается <span class="tex-font-style-it">интересным</span>.</p><p>Найдите количество интересных загонов. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$3 \le n \le 6000$$$) — количество столбов, которые Грегор может выбрать в качестве вершин загона.</p><p>Следующие $$$n$$$ строк содержат по два целых числа $$$x$$$ и $$$y$$$ ($$$0 \le x,y \le 10^7$$$, где $$$(x,y)$$$ — координата очередного столба. Все столбы расположены в различных точках. Никакие три столба не лежат на одной прямой.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Напечатайте одно целое число — количество интересных загонов. Два загона считаются различными, если они образованы различными множествами трех столбов. </p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 0 0 2 0 0 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 8 0 6 5 2 5 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 170 59 129 54 5 98 129 37 58 193 154 58 24 3 13 138 136 144 174 150 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 29 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере существует только $$$1$$$ загон. Этот загон является интересным, поскольку его площадь равна $$$4$$$ и есть $$$1$$$ пойманная корова, помеченная красным. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/9e3ef13118f82e89c5ddcd89348c8703ec6ea5bf.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во втором примере существует $$$4$$$ возможных загона. Однако, только один из них является интересным. Этот загон имеет площадь, равную $$$8$$$, и $$$5$$$ пойманных коров.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/54519830da1f6e61df2d41e2713f59bd51424189.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=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 11:30: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:'8124c89e0b62149c',t:'MTY5NjY2NzQ0My4wNjMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*3300"]
1548E
1548
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 \times m$$$.</p><p>Для каждого $$$i$$$ от $$$1$$$ до $$$n$$$ включительно маляр Амин нанес $$$a_i$$$ слоев краски на весь $$$i$$$-й ряд. Для каждого $$$j$$$ от $$$1$$$ до $$$m$$$ включительно маляр Бенджи нанес $$$b_j$$$ слоев краски на весь $$$j$$$-й столбец. Таким образом, клетка $$$(i,j)$$$ оказалась покрашенной в $$$a_i+b_j$$$ слоев краски. </p><p>Грегор считает, что клетка $$$(i,j)$$$ <span class="tex-font-style-it">плохо покрашена</span>, если $$$a_i+b_j \le x$$$. Определим <span class="tex-font-style-it">плохо покрашенную область</span> как <span class="tex-font-style-bf">максимальную по включению</span> связную компоненту плохо покрашенных клеток, то есть такую связную компоненту плохо покрашенных клеток, что все клетки, соседние с этой компонентой, не являются плохо покрашенными. Две клетки являются соседними, если они имеют общую сторону. </p><p>Грегор потрясен состоянием потолка, покрашенного малярами, и хочет знать количество плохо покрашенных областей. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит три целых числа $$$n$$$, $$$m$$$ и $$$x$$$ ($$$1 \le n,m \le 2\cdot 10^5$$$, $$$1 \le x \le 2\cdot 10^5$$$) — размеры потолка Грегора и максимальное количество слоев краски в плохо покрашенной клетке.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot 10^5$$$) — количество слоев краски, которое Амин наносит на каждый ряд.</p><p>Третья строка содержит $$$m$$$ целых чисел $$$b_1, b_2, \ldots, b_m$$$ ($$$1 \le b_j \le 2\cdot 10^5$$$) — количество слоев краски, которое Бенджи наносит на каждый столбец.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество плохо покрашенных областей.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 11 9 8 5 10 6 7 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 12 9 8 5 10 6 7 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 2 1 2 1 1 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 23 6 1 4 3 5 2 2 3 1 6 1 5 5 6 1 3 2 6 2 3 1 6 1 4 1 6 1 5 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>Рисунок ниже иллюстрирует первый пример. Числа слева от каждого ряда представляют собой список $$$a$$$, а числа над каждым столбцом — список $$$b$$$. Числа внутри каждой клетки равны количеству слоев краски в этой клетке.</p><p>Цветные клетки соответствуют плохо покрашенным клеткам. Красные и синие клетки соответственно образуют $$$2$$$ плохо покрашенных области. </p><center> <img class="tex-graphics" height="227px" src="https://espresso.codeforces.com/3d4487c98e21fc424dabf98b3f11a81a0de5fb53.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px"/> </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="c5a0c6fded056a464abcad5ff5741c16"/> <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="ee09f07644402b5410765db8004aff1e6ad5a858"/> <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='c5a0c6fded056a464abcad5ff5741c16'>&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%2F1548%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='c5a0c6fded056a464abcad5ff5741c16'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1548">Codeforces Round 736 (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='c5a0c6fded056a464abcad5ff5741c16'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1548/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='c5a0c6fded056a464abcad5ff5741c16'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1062387"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c5a0c6fded056a464abcad5ff5741c16'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1062387"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/93361" title="Codeforces Round #736" target="_blank">Codeforces Round #736 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14106" resourceName="Codeforces Round #736" resourceManual="true" src="//codeforces.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/93586" title="Codeforces Round 736 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14141" resourceName="Codeforces Round 736 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/1548">Задачи</a></li> <li><a href="/contest/1548/submit">Отослать</a></li> <li><a href="/contest/1548/my">Мои посылки</a></li> <li><a href="/contest/1548/status">Статус</a></li> <li><a href="/contest/1548/hacks">Взломы</a></li> <li><a href="/contest/1548/room/1">Комната</a></li> <li><a href="/contest/1548/standings">Положение</a></li> <li><a href="/contest/1548/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_a0ca624758e9183861ad98145db981b0e89fcd0e"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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 \times m$$$.</p><p>Для каждого $$$i$$$ от $$$1$$$ до $$$n$$$ включительно маляр Амин нанес $$$a_i$$$ слоев краски на весь $$$i$$$-й ряд. Для каждого $$$j$$$ от $$$1$$$ до $$$m$$$ включительно маляр Бенджи нанес $$$b_j$$$ слоев краски на весь $$$j$$$-й столбец. Таким образом, клетка $$$(i,j)$$$ оказалась покрашенной в $$$a_i+b_j$$$ слоев краски. </p><p>Грегор считает, что клетка $$$(i,j)$$$ <span class="tex-font-style-it">плохо покрашена</span>, если $$$a_i+b_j \le x$$$. Определим <span class="tex-font-style-it">плохо покрашенную область</span> как <span class="tex-font-style-bf">максимальную по включению</span> связную компоненту плохо покрашенных клеток, то есть такую связную компоненту плохо покрашенных клеток, что все клетки, соседние с этой компонентой, не являются плохо покрашенными. Две клетки являются соседними, если они имеют общую сторону. </p><p>Грегор потрясен состоянием потолка, покрашенного малярами, и хочет знать количество плохо покрашенных областей. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит три целых числа $$$n$$$, $$$m$$$ и $$$x$$$ ($$$1 \le n,m \le 2\cdot 10^5$$$, $$$1 \le x \le 2\cdot 10^5$$$) — размеры потолка Грегора и максимальное количество слоев краски в плохо покрашенной клетке.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot 10^5$$$) — количество слоев краски, которое Амин наносит на каждый ряд.</p><p>Третья строка содержит $$$m$$$ целых чисел $$$b_1, b_2, \ldots, b_m$$$ ($$$1 \le b_j \le 2\cdot 10^5$$$) — количество слоев краски, которое Бенджи наносит на каждый столбец.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество плохо покрашенных областей.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 4 11 9 8 5 10 6 7 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 12 9 8 5 10 6 7 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 2 1 2 1 1 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 23 6 1 4 3 5 2 2 3 1 6 1 5 5 6 1 3 2 6 2 3 1 6 1 4 1 6 1 5 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>Рисунок ниже иллюстрирует первый пример. Числа слева от каждого ряда представляют собой список $$$a$$$, а числа над каждым столбцом — список $$$b$$$. Числа внутри каждой клетки равны количеству слоев краски в этой клетке.</p><p>Цветные клетки соответствуют плохо покрашенным клеткам. Красные и синие клетки соответственно образуют $$$2$$$ плохо покрашенных области. </p><center> <img class="tex-graphics" height="227px" src="https://espresso.codeforces.com/3d4487c98e21fc424dabf98b3f11a81a0de5fb53.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px" /> </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c8a6ddbc15ee',t:'MTY5NjY2NzQ0NC40NDkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3400"]
1549A
1549
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>Грегор изучает RSA — известный алгоритм криптографии, и несмотря на то, что он пока не понимает, как работает RSA, он очаровался простыми числами и работой с ними.</p><p>Любимое <span class="tex-font-style-bf">простое</span> число Грегора равно $$$P$$$. Грегор хочет найти два <span class="tex-font-style-bf">основания</span> $$$P$$$. Формально, Грегор хочет найти два целых числа $$$a$$$ и $$$b$$$, удовлетворяющих двум следующим условиям.</p><ul> <li> $$$P \bmod a = P \bmod b$$$, где $$$x \bmod y$$$ обозначает остаток от деления $$$x$$$ на $$$y$$$, и </li><li> $$$2 \le a &lt; b \le P$$$. </li></ul><p>Помогите Грегору найти два основания его любимого простого числа!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких наборов входных данных. Первая строка содержит количество наборов входных данных $$$t$$$ ($$$1 \le t \le 1000$$$).</p><p>Каждая последующая строка содержит одно целое число $$$P$$$ ($$$5 \le P \le {10}^9$$$), где $$$P$$$ гарантированно простое. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Вывод должен состоять из $$$t$$$ строк. Каждая строка должна содержать два целых числа $$$a$$$ и $$$b$$$ ($$$2 \le a &lt; b \le 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 17 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 5 2 4</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$P=17$$$. $$$a=3$$$ и $$$b=5$$$ допустимые <span class="tex-font-style-it">основания</span>, потому что $$$17 \bmod 3 = 17 \bmod 5 = 2$$$. Существуют другие допустимые пары. </p><p>Во втором примере $$$P=5$$$, единственное решение здесь — $$$a=2$$$ и $$$b=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="af07e165327d5090f4af7119e715d14f"/> <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="2df1b3d2945312903b5d8e51f07fc9d370850715"/> <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='af07e165327d5090f4af7119e715d14f'>&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%2F1549%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='af07e165327d5090f4af7119e715d14f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1549">Codeforces Round 736 (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='af07e165327d5090f4af7119e715d14f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1549/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др."> теория чисел </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *800 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='af07e165327d5090f4af7119e715d14f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1062374"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='af07e165327d5090f4af7119e715d14f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1062374"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/93361" title="Codeforces Round #736" target="_blank">Codeforces Round #736 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14107" resourceName="Codeforces Round #736" resourceManual="true" src="//codeforces.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/93586" title="Codeforces Round 736 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14142" resourceName="Codeforces Round 736 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/1549">Задачи</a></li> <li><a href="/contest/1549/submit">Отослать</a></li> <li><a href="/contest/1549/my">Мои посылки</a></li> <li><a href="/contest/1549/status">Статус</a></li> <li><a href="/contest/1549/hacks">Взломы</a></li> <li><a href="/contest/1549/room/1">Комната</a></li> <li><a href="/contest/1549/standings">Положение</a></li> <li><a href="/contest/1549/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_dc0b2d497dd5789bfb6fb1bc65cd8048aecb1be5"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Грегор изучает RSA — известный алгоритм криптографии, и несмотря на то, что он пока не понимает, как работает RSA, он очаровался простыми числами и работой с ними.</p><p>Любимое <span class="tex-font-style-bf">простое</span> число Грегора равно $$$P$$$. Грегор хочет найти два <span class="tex-font-style-bf">основания</span> $$$P$$$. Формально, Грегор хочет найти два целых числа $$$a$$$ и $$$b$$$, удовлетворяющих двум следующим условиям.</p><ul> <li> $$$P \bmod a = P \bmod b$$$, где $$$x \bmod y$$$ обозначает остаток от деления $$$x$$$ на $$$y$$$, и </li><li> $$$2 \le a &lt; b \le P$$$. </li></ul><p>Помогите Грегору найти два основания его любимого простого числа!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких наборов входных данных. Первая строка содержит количество наборов входных данных $$$t$$$ ($$$1 \le t \le 1000$$$).</p><p>Каждая последующая строка содержит одно целое число $$$P$$$ ($$$5 \le P \le {10}^9$$$), где $$$P$$$ гарантированно простое. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Вывод должен состоять из $$$t$$$ строк. Каждая строка должна содержать два целых числа $$$a$$$ и $$$b$$$ ($$$2 \le a &lt; b \le 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 17 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 5 2 4</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$P=17$$$. $$$a=3$$$ и $$$b=5$$$ допустимые <span class="tex-font-style-it">основания</span>, потому что $$$17 \bmod 3 = 17 \bmod 5 = 2$$$. Существуют другие допустимые пары. </p><p>Во втором примере $$$P=5$$$, единственное решение здесь — $$$a=2$$$ и $$$b=4$$$. </p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c8afcb4c75b3',t:'MTY5NjY2NzQ0NS45MzEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*800"]
1549B
1549
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$$$. Клетка на пересечении $$$i$$$-й сверху ряду и $$$j$$$-го слева столбца обозначается как $$$(i,j)$$$.</p><p>На данный момент у Грегора есть несколько пешек в $$$n$$$-м ряду. Также в $$$1$$$-м ряду стоят вражеские пешки. За один шаг Грегор перемещает одну из <span class="tex-font-style-bf">своих</span> пешек. Пешка может ходить на одну клетку вверх (из $$$(i,j)$$$ в $$$(i-1,j)$$$), если клетка назначения не занята другой пешкой. В дополнение, пешка может переместиться на одну клетку вверх по диагонали (из $$$(i,j)$$$ в $$$(i-1,j-1)$$$ или в $$$(i-1,j+1)$$$), если и только если в этой клетке стоит вражеская пешка. Вражеская пешка в таком случае убирается с доски. </p><p>Грегор хочет узнать, какое максимальное количество его пешек может достичь $$$1$$$-го ряда.</p><p>Заметьте, что в этой игре ходит только Грегор, <span class="tex-font-style-bf">вражеские пешки никогда не перемещаются</span>. Также, когда пешка Грегора достигает $$$1$$$-го ряда, она останавливается и больше не может перемещаться. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка ввода содержит одно целое число $$$t$$$ ($$$1\le t\le 2\cdot 10^4$$$) — количество наборов входных данных. Далее следует описание этих $$$t$$$ наборов.</p><p>Каждый набор входных данных состоит из трех строк. Первая строка содержит одно целое число $$$n$$$ ($$$2\le n\le 2\cdot{10}^{5}$$$) — размер доски.</p><p>Вторая строка содержит бинарную строку длины $$$n$$$, в которой $$$1$$$ на $$$i$$$-й позиции соответствует вражеской пешке в $$$i$$$-й слева клетке в первом ряду, а $$$0$$$ соответствует пустой клетке.</p><p>Третья строка содержит бинарную строку длины $$$n$$$, в которой $$$1$$$ на $$$i$$$-й позиции соответствует пешке Грегора в $$$i$$$-й слева клетке в последнем ряду, а $$$0$$$ соответствует пустой клетке.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных меньше $$$2\cdot{10}^{5}$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число: <span class="tex-font-style-bf">максимальное</span> количество пешек Грегора, которые могут достичь $$$1$$$-го ряда.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 000 111 4 1111 1111 3 010 010 5 11001 00000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 4 0 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере Грегор может просто переместить вперед все его $$$3$$$ пешки. Таким образом, ответ равен $$$3$$$.</p><p>Во втором примере Грегор может гарантировать, что все его $$$4$$$ пешки достигнут вражеского ряда, следуя раскрашенным путям как показано ниже. Помните — только Грегор делает ходы в этой «игре»!</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/dcfcf5fa10eb8a078be59e01db667ef14eeb054f.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px"/> </center><p>В третьем примере единственная пешка Грегора застряла перед вражеской пешкой и не может достигнуть желаемого ряда. </p><p>В четвертом примере у Грегора нет пешек, поэтому ответ равен $$$0$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="a18ec7f39d6542d3b09b0eaf47bb7f51"/> <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="2df1b3d2945312903b5d8e51f07fc9d370850715"/> <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='a18ec7f39d6542d3b09b0eaf47bb7f51'>&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%2F1549%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='a18ec7f39d6542d3b09b0eaf47bb7f51'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1549">Codeforces Round 736 (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='a18ec7f39d6542d3b09b0eaf47bb7f51'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1549/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Графы"> графы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы"> жадные алгоритмы </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Паросочетания, теорема Кёнига, вершинные и реберные покрытия в двудольных графах"> паросочетания </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы"> поиск в глубину и подобное </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Потоки в графах"> потоки </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция"> реализация </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *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='a18ec7f39d6542d3b09b0eaf47bb7f51'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1062375"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a18ec7f39d6542d3b09b0eaf47bb7f51'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1062375"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/93361" title="Codeforces Round #736" target="_blank">Codeforces Round #736 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14107" resourceName="Codeforces Round #736" resourceManual="true" src="//codeforces.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/93586" title="Codeforces Round 736 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14142" resourceName="Codeforces Round 736 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/1549">Задачи</a></li> <li><a href="/contest/1549/submit">Отослать</a></li> <li><a href="/contest/1549/my">Мои посылки</a></li> <li><a href="/contest/1549/status">Статус</a></li> <li><a href="/contest/1549/hacks">Взломы</a></li> <li><a href="/contest/1549/room/1">Комната</a></li> <li><a href="/contest/1549/standings">Положение</a></li> <li><a href="/contest/1549/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_cabc4e187ad2e0410f635a54cd93c7116aaa1329"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$. Клетка на пересечении $$$i$$$-й сверху ряду и $$$j$$$-го слева столбца обозначается как $$$(i,j)$$$.</p><p>На данный момент у Грегора есть несколько пешек в $$$n$$$-м ряду. Также в $$$1$$$-м ряду стоят вражеские пешки. За один шаг Грегор перемещает одну из <span class="tex-font-style-bf">своих</span> пешек. Пешка может ходить на одну клетку вверх (из $$$(i,j)$$$ в $$$(i-1,j)$$$), если клетка назначения не занята другой пешкой. В дополнение, пешка может переместиться на одну клетку вверх по диагонали (из $$$(i,j)$$$ в $$$(i-1,j-1)$$$ или в $$$(i-1,j+1)$$$), если и только если в этой клетке стоит вражеская пешка. Вражеская пешка в таком случае убирается с доски. </p><p>Грегор хочет узнать, какое максимальное количество его пешек может достичь $$$1$$$-го ряда.</p><p>Заметьте, что в этой игре ходит только Грегор, <span class="tex-font-style-bf">вражеские пешки никогда не перемещаются</span>. Также, когда пешка Грегора достигает $$$1$$$-го ряда, она останавливается и больше не может перемещаться. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка ввода содержит одно целое число $$$t$$$ ($$$1\le t\le 2\cdot 10^4$$$) — количество наборов входных данных. Далее следует описание этих $$$t$$$ наборов.</p><p>Каждый набор входных данных состоит из трех строк. Первая строка содержит одно целое число $$$n$$$ ($$$2\le n\le 2\cdot{10}^{5}$$$) — размер доски.</p><p>Вторая строка содержит бинарную строку длины $$$n$$$, в которой $$$1$$$ на $$$i$$$-й позиции соответствует вражеской пешке в $$$i$$$-й слева клетке в первом ряду, а $$$0$$$ соответствует пустой клетке.</p><p>Третья строка содержит бинарную строку длины $$$n$$$, в которой $$$1$$$ на $$$i$$$-й позиции соответствует пешке Грегора в $$$i$$$-й слева клетке в последнем ряду, а $$$0$$$ соответствует пустой клетке.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных меньше $$$2\cdot{10}^{5}$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число: <span class="tex-font-style-bf">максимальное</span> количество пешек Грегора, которые могут достичь $$$1$$$-го ряда.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 000 111 4 1111 1111 3 010 010 5 11001 00000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 4 0 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере Грегор может просто переместить вперед все его $$$3$$$ пешки. Таким образом, ответ равен $$$3$$$.</p><p>Во втором примере Грегор может гарантировать, что все его $$$4$$$ пешки достигнут вражеского ряда, следуя раскрашенным путям как показано ниже. Помните — только Грегор делает ходы в этой «игре»!</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/dcfcf5fa10eb8a078be59e01db667ef14eeb054f.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px" /> </center><p>В третьем примере единственная пешка Грегора застряла перед вражеской пешкой и не может достигнуть желаемого ряда. </p><p>В четвертом примере у Грегора нет пешек, поэтому ответ равен $$$0$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c8b8cae616c7',t:'MTY5NjY2NzQ0Ny4yODUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0430\u0440\u043e\u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u044f, \u0442\u0435\u043e\u0440\u0435\u043c\u0430 \u041a\u0451\u043d\u0438\u0433\u0430, \u0432\u0435\u0440\u0448\u0438\u043d\u043d\u044b\u0435 \u0438 \u0440\u0435\u0431\u0435\u0440\u043d\u044b\u0435 \u043f\u043e\u043a\u0440\u044b\u0442\u0438\u044f \u0432 \u0434\u0432\u0443\u0434\u043e\u043b\u044c\u043d\u044b\u0445 \u0433\u0440\u0430\u0444\u0430\u0445", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0442\u043e\u043a\u0438 \u0432 \u0433\u0440\u0430\u0444\u0430\u0445", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0430\u0440\u043e\u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u044f", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u043f\u043e\u0442\u043e\u043a\u0438", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*800"]
1549C
1549
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><div class="epigraph"><div class="epigraph-text">Когда играешь в игру престолов, ты побеждаешь или умираешь. Третьего не дано.</div><div class="epigraph-source">Серсея Ланнистер, <span class="tex-font-style-it">Игра престолов</span>, Джордж Р. Р. Мартин</div></div><p>Есть $$$n$$$ дворян, пронумерованных от $$$1$$$ до $$$n$$$. Дворянин $$$i$$$ обладает могуществом $$$i$$$. Дворяне «дружат» между собой — всего есть $$$m$$$ пар дружных дворян. Дружба между дворянами $$$a$$$ и $$$b$$$ всегда взаимная. </p><p>Дворянин считается <span class="tex-font-style-it">уязвимым</span>, если выполнены оба следующих условия. </p><ul> <li> у этого дворянина есть хотя бы один друг, и </li><li> <span class="tex-font-style-bf">все</span> друзья этого дворянина обладают могуществом, превосходящим могущество этого дворянина. </li></ul><p>Вам нужно будет обрабатывать следующие три типа запросов. </p><ol> <li> Добавить дружбу между $$$u$$$ и $$$v$$$. </li><li> Удалить дружбу между $$$u$$$ и $$$v$$$. </li><li> Посчитать ответ на следующий процесс. </li></ol><p>Процесс: все уязвимые дворяне одновременно умирают, и все их дружбы заканчиваются. После этого, возможно, некоторые другие дворяне становятся уязвимыми. Процесс повторяется до тех пор, пока есть уязвимые дворяне. Можно доказать, что процесс завершится за конечное число шагов. После завершения процесса вам необходимо посчитать количество оставшихся дворян. </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>Следующие $$$m$$$ строк содержат по два целых числа $$$u$$$ и $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$), описывающие дружбу между дворянами. Никакая пара друзей не повторяется дважды.</p><p>Следующая строка содержит целое число $$$q$$$ ($$$1 \le q \le 2\cdot {10}^{5}$$$) — количество запросов. </p><p>Следующие $$$q$$$ строк содержат сами запросы по одному в строке. Каждый запрос имеет один из следующих видов: </p><ul> <li> $$$1$$$ $$$u$$$ $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$) — добавить дружбу между $$$u$$$ и $$$v$$$. Гарантируется, что $$$u$$$ и $$$v$$$ не друзья в этот момент. </li><li> $$$2$$$ $$$u$$$ $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$) — удалить дружбу между $$$u$$$ и $$$v$$$. Гарантируется, что $$$u$$$ и $$$v$$$ дружат в этот момент. </li><li> $$$3$$$ — вывести ответ на процесс, описанный в условии. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос $$$3$$$-го типа выведите целое число, по одному на строку. Гарантируется, что будет хотя бы один запрос типа $$$3$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 1 1 3 3 4 4 3 1 2 3 2 3 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 3 3 4 4 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ситуация в первом запросе типа 3 изображена на рисунке ниже.</p><p>В первом раунде процесса дворянин $$$1$$$ слабее, чем все его друзья ($$$2$$$ и $$$3$$$), и поэтому он умирает. Никакой другой дворянин в раунде 1 не является уязвимым. В раунде 2 дворянин $$$3$$$ слабее своего единственного друга, дворянина $$$4$$$, и поэтому он умирает. На этом этапе процесс завершается, ответ равен $$$2$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/cbaf66d5c268440ab9f4754a89be088c6d87b738.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Во втором запросе типа 3 единственным выжившим является дворянин $$$4$$$.</p><p>    </p><p>Второй пример состоит только из одного запроса типа $$$3$$$. В первом раунде умирают два дворянина, во втором раунде умирает один дворянин. Итоговый ответ равен $$$1$$$, поскольку только один дворянин выжил. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8631f2c909305073cf264f22183338c334c8d19e.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="f841be24bbdcc9eb240bdfcfbbb209dc"/> <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="2df1b3d2945312903b5d8e51f07fc9d370850715"/> <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='f841be24bbdcc9eb240bdfcfbbb209dc'>&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%2F1549%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='f841be24bbdcc9eb240bdfcfbbb209dc'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1549">Codeforces Round 736 (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='f841be24bbdcc9eb240bdfcfbbb209dc'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1549/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='f841be24bbdcc9eb240bdfcfbbb209dc'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1062376"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f841be24bbdcc9eb240bdfcfbbb209dc'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1062376"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/93361" title="Codeforces Round #736" target="_blank">Codeforces Round #736 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14107" resourceName="Codeforces Round #736" resourceManual="true" src="//codeforces.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/93586" title="Codeforces Round 736 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14142" resourceName="Codeforces Round 736 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/1549">Задачи</a></li> <li><a href="/contest/1549/submit">Отослать</a></li> <li><a href="/contest/1549/my">Мои посылки</a></li> <li><a href="/contest/1549/status">Статус</a></li> <li><a href="/contest/1549/hacks">Взломы</a></li> <li><a href="/contest/1549/room/1">Комната</a></li> <li><a href="/contest/1549/standings">Положение</a></li> <li><a href="/contest/1549/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_24d8d9a72d63d6f30f9fe3b9f2b89984ad43dc50"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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><div class="epigraph"><div class="epigraph-text">Когда играешь в игру престолов, ты побеждаешь или умираешь. Третьего не дано.</div><div class="epigraph-source">Серсея Ланнистер, <span class="tex-font-style-it">Игра престолов</span>, Джордж Р. Р. Мартин</div></div><p>Есть $$$n$$$ дворян, пронумерованных от $$$1$$$ до $$$n$$$. Дворянин $$$i$$$ обладает могуществом $$$i$$$. Дворяне «дружат» между собой — всего есть $$$m$$$ пар дружных дворян. Дружба между дворянами $$$a$$$ и $$$b$$$ всегда взаимная. </p><p>Дворянин считается <span class="tex-font-style-it">уязвимым</span>, если выполнены оба следующих условия. </p><ul> <li> у этого дворянина есть хотя бы один друг, и </li><li> <span class="tex-font-style-bf">все</span> друзья этого дворянина обладают могуществом, превосходящим могущество этого дворянина. </li></ul><p>Вам нужно будет обрабатывать следующие три типа запросов. </p><ol> <li> Добавить дружбу между $$$u$$$ и $$$v$$$. </li><li> Удалить дружбу между $$$u$$$ и $$$v$$$. </li><li> Посчитать ответ на следующий процесс. </li></ol><p>Процесс: все уязвимые дворяне одновременно умирают, и все их дружбы заканчиваются. После этого, возможно, некоторые другие дворяне становятся уязвимыми. Процесс повторяется до тех пор, пока есть уязвимые дворяне. Можно доказать, что процесс завершится за конечное число шагов. После завершения процесса вам необходимо посчитать количество оставшихся дворян. </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>Следующие $$$m$$$ строк содержат по два целых числа $$$u$$$ и $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$), описывающие дружбу между дворянами. Никакая пара друзей не повторяется дважды.</p><p>Следующая строка содержит целое число $$$q$$$ ($$$1 \le q \le 2\cdot {10}^{5}$$$) — количество запросов. </p><p>Следующие $$$q$$$ строк содержат сами запросы по одному в строке. Каждый запрос имеет один из следующих видов: </p><ul> <li> $$$1$$$ $$$u$$$ $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$) — добавить дружбу между $$$u$$$ и $$$v$$$. Гарантируется, что $$$u$$$ и $$$v$$$ не друзья в этот момент. </li><li> $$$2$$$ $$$u$$$ $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$) — удалить дружбу между $$$u$$$ и $$$v$$$. Гарантируется, что $$$u$$$ и $$$v$$$ дружат в этот момент. </li><li> $$$3$$$ — вывести ответ на процесс, описанный в условии. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос $$$3$$$-го типа выведите целое число, по одному на строку. Гарантируется, что будет хотя бы один запрос типа $$$3$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 1 1 3 3 4 4 3 1 2 3 2 3 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 3 3 4 4 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ситуация в первом запросе типа 3 изображена на рисунке ниже.</p><p>В первом раунде процесса дворянин $$$1$$$ слабее, чем все его друзья ($$$2$$$ и $$$3$$$), и поэтому он умирает. Никакой другой дворянин в раунде 1 не является уязвимым. В раунде 2 дворянин $$$3$$$ слабее своего единственного друга, дворянина $$$4$$$, и поэтому он умирает. На этом этапе процесс завершается, ответ равен $$$2$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/cbaf66d5c268440ab9f4754a89be088c6d87b738.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во втором запросе типа 3 единственным выжившим является дворянин $$$4$$$.</p><p>    </p><p>Второй пример состоит только из одного запроса типа $$$3$$$. В первом раунде умирают два дворянина, во втором раунде умирает один дворянин. Итоговый ответ равен $$$1$$$, поскольку только один дворянин выжил. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8631f2c909305073cf264f22183338c334c8d19e.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c8c15d0303dd',t:'MTY5NjY2NzQ0OC42MDUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "*1400"]
1549D
1549
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>Оказывается, натуральные числа могут также дружить друг с другом! Вам дан массив $$$a$$$ из различных натуральных чисел.</p><p>Будем называть <span class="tex-font-style-bf">подмассив</span> $$$a_i, a_{i+1}, \ldots, a_j$$$ <span class="tex-font-style-it">группой друзей</span> тогда и только тогда, когда существует целое число $$$m \ge 2$$$ такое, что $$$a_i \bmod m = a_{i+1} \bmod m = \ldots = a_j \bmod m$$$, где $$$x \bmod y$$$ обозначает остаток от деления $$$x$$$ на $$$y$$$.</p><p>Ваш друг Грегор хочет знать размер наибольшей группы друзей в $$$a$$$. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит количество наборов входных данных $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$).</p><p>Первая строка каждого набора содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) – размера массива $$$a$$$.</p><p>Вторая строка набора содержит $$$n$$$ натуральных чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le {10}^{18}$$$) – содержимое массива $$$a$$$. Гарантируется, что все числа в $$$a$$$ <span class="tex-font-style-bf">различны</span>.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных меньше $$$2\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Ваш вывод должен состоять из $$$t$$$ строк. Каждая строка должна содержать одно целое число — размер наибольшей группы друзей из $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 1 5 2 4 6 4 8 2 5 10 2 1000 2000 8 465 55 3 54 234 12 45 78 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 3 2 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе массив равен $$$[1,5,2,4,6]$$$. Наибольшая группа друзей здесь $$$[2,4,6]$$$, потому что все эти числа сравнимы с $$$0$$$ по модулю $$$2$$$, таким образом $$$m=2$$$.</p><p>В первом наборе массив равен $$$[8,2,5,10]$$$. Наибольшая группа друзей здесь $$$[8,2,5]$$$, потому что все эти числа сравнимы с $$$2$$$ по модулю $$$3$$$, таким образом $$$m=3$$$.</p><p>В третьем наборе наибольшая группа друзей равна $$$[1000,2000]$$$. Существует несколько возможных подходящих значений $$$m$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="ee62a439cbe26f89636418171f26110d"/> <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="2df1b3d2945312903b5d8e51f07fc9d370850715"/> <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='ee62a439cbe26f89636418171f26110d'>&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%2F1549%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='ee62a439cbe26f89636418171f26110d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1549">Codeforces Round 736 (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='ee62a439cbe26f89636418171f26110d'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1549/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, params, function (result) { if (result["success"] !== "true") { Codeforces.showMessage("Не удалось сохранить состояние блока."); } }, "json"); return false; }); }) </script> </div> <div class="roundbox sidebox borderTopRound " style=""> <div class="caption titled">&rarr; Теги задачи <div class="top-links"> </div> </div> <div style="padding: 0.5em;"> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск"> бинарный поиск </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Два указателя"> два указателя </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др."> математика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Сложность"> *1800 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ee62a439cbe26f89636418171f26110d'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="1062377"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ee62a439cbe26f89636418171f26110d'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="1062377"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/93361" title="Codeforces Round #736" target="_blank">Codeforces Round #736 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14107" resourceName="Codeforces Round #736" resourceManual="true" src="//codeforces.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/93586" title="Codeforces Round 736 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="14142" resourceName="Codeforces Round 736 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/1549">Задачи</a></li> <li><a href="/contest/1549/submit">Отослать</a></li> <li><a href="/contest/1549/my">Мои посылки</a></li> <li><a href="/contest/1549/status">Статус</a></li> <li><a href="/contest/1549/hacks">Взломы</a></li> <li><a href="/contest/1549/room/1">Комната</a></li> <li><a href="/contest/1549/standings">Положение</a></li> <li><a href="/contest/1549/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_88171eed8a14da6111ba5c0d66d505eea13b0e12"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Оказывается, натуральные числа могут также дружить друг с другом! Вам дан массив $$$a$$$ из различных натуральных чисел.</p><p>Будем называть <span class="tex-font-style-bf">подмассив</span> $$$a_i, a_{i+1}, \ldots, a_j$$$ <span class="tex-font-style-it">группой друзей</span> тогда и только тогда, когда существует целое число $$$m \ge 2$$$ такое, что $$$a_i \bmod m = a_{i+1} \bmod m = \ldots = a_j \bmod m$$$, где $$$x \bmod y$$$ обозначает остаток от деления $$$x$$$ на $$$y$$$.</p><p>Ваш друг Грегор хочет знать размер наибольшей группы друзей в $$$a$$$. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит количество наборов входных данных $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$).</p><p>Первая строка каждого набора содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) – размера массива $$$a$$$.</p><p>Вторая строка набора содержит $$$n$$$ натуральных чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le {10}^{18}$$$) – содержимое массива $$$a$$$. Гарантируется, что все числа в $$$a$$$ <span class="tex-font-style-bf">различны</span>.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных меньше $$$2\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Ваш вывод должен состоять из $$$t$$$ строк. Каждая строка должна содержать одно целое число — размер наибольшей группы друзей из $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 1 5 2 4 6 4 8 2 5 10 2 1000 2000 8 465 55 3 54 234 12 45 78 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 3 2 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе массив равен $$$[1,5,2,4,6]$$$. Наибольшая группа друзей здесь $$$[2,4,6]$$$, потому что все эти числа сравнимы с $$$0$$$ по модулю $$$2$$$, таким образом $$$m=2$$$.</p><p>В первом наборе массив равен $$$[8,2,5,10]$$$. Наибольшая группа друзей здесь $$$[8,2,5]$$$, потому что все эти числа сравнимы с $$$2$$$ по модулю $$$3$$$, таким образом $$$m=3$$$.</p><p>В третьем наборе наибольшая группа друзей равна $$$[1000,2000]$$$. Существует несколько возможных подходящих значений $$$m$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/86568"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:30: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:'8124c8c96fa7064b',t:'MTY5NjY2NzQ0OS44NzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\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", "*1800"]